llvm.org GIT mirror llvm / fd93908
Remove trailing whitespace git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@21427 91177308-0d34-0410-b5e6-96231b3b80d8 Misha Brukman 14 years ago
126 changed file(s) with 1898 addition(s) and 1898 deletion(s). Raw diff Collapse all Expand all
0 //===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // Represent a range of possible values that may occur when the program is run
3131 static ConstantIntegral *Next(ConstantIntegral *CI) {
3232 if (CI->getType() == Type::BoolTy)
3333 return CI == ConstantBool::True ? ConstantBool::False : ConstantBool::True;
34
34
3535 Constant *Result = ConstantExpr::getAdd(CI,
3636 ConstantInt::get(CI->getType(), 1));
3737 return cast(Result);
8383 : Lower(cast(L)), Upper(cast(U)) {
8484 assert(Lower->getType() == Upper->getType() &&
8585 "Incompatible types for ConstantRange!");
86
86
8787 // Make sure that if L & U are equal that they are either Min or Max...
8888 assert((L != U || (L == ConstantIntegral::getMaxValue(L->getType()) ||
8989 L == ConstantIntegral::getMinValue(L->getType()))) &&
125125 bool ConstantRange::isFullSet() const {
126126 return Lower == Upper && Lower == ConstantIntegral::getMaxValue(getType());
127127 }
128
128
129129 /// isEmptySet - Return true if this set contains no members.
130130 ///
131131 bool ConstantRange::isEmptySet() const {
139139 return GT(Lower, Upper);
140140 }
141141
142
142
143143 /// getSingleElement - If this set contains a single element, return it,
144144 /// otherwise return null.
145145 ConstantIntegral *ConstantRange::getSingleElement() const {
157157 return 1;
158158 return 2; // Must be full set...
159159 }
160
160
161161 // Simply subtract the bounds...
162162 Constant *Result = ConstantExpr::getSub(Upper, Lower);
163163 return cast(Result)->getRawValue();
0 //===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // Represent a range of possible values that may occur when the program is run
3131 static ConstantIntegral *Next(ConstantIntegral *CI) {
3232 if (CI->getType() == Type::BoolTy)
3333 return CI == ConstantBool::True ? ConstantBool::False : ConstantBool::True;
34
34
3535 Constant *Result = ConstantExpr::getAdd(CI,
3636 ConstantInt::get(CI->getType(), 1));
3737 return cast(Result);
8383 : Lower(cast(L)), Upper(cast(U)) {
8484 assert(Lower->getType() == Upper->getType() &&
8585 "Incompatible types for ConstantRange!");
86
86
8787 // Make sure that if L & U are equal that they are either Min or Max...
8888 assert((L != U || (L == ConstantIntegral::getMaxValue(L->getType()) ||
8989 L == ConstantIntegral::getMinValue(L->getType()))) &&
125125 bool ConstantRange::isFullSet() const {
126126 return Lower == Upper && Lower == ConstantIntegral::getMaxValue(getType());
127127 }
128
128
129129 /// isEmptySet - Return true if this set contains no members.
130130 ///
131131 bool ConstantRange::isEmptySet() const {
139139 return GT(Lower, Upper);
140140 }
141141
142
142
143143 /// getSingleElement - If this set contains a single element, return it,
144144 /// otherwise return null.
145145 ConstantIntegral *ConstantRange::getSingleElement() const {
157157 return 1;
158158 return 2; // Must be full set...
159159 }
160
160
161161 // Simply subtract the bounds...
162162 Constant *Result = ConstantExpr::getSub(Upper, Lower);
163163 return cast(Result)->getRawValue();
0 //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type -------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the part of level raising that checks to see if it is
6868 // here...
6969 uint64_t Offset = OffsetVal * OldTypeSize;
7070 uint64_t Scale = ScaleVal * OldTypeSize;
71
71
7272 // In order to be successful, both the scale and the offset must be a multiple
7373 // of the requested data type's size.
7474 //
144144 // Expression type must be holdable in a register.
145145 if (!Ty->isFirstClassType())
146146 return false;
147
147
148148 ValueTypeCache::iterator CTMI = CTMap.find(V);
149149 if (CTMI != CTMap.end()) return CTMI->second == Ty;
150150
153153 //
154154 if (isa(V) && !isa(V))
155155 return true;
156
156
157157 CTMap[V] = Ty;
158158 if (V->getType() == Ty) return true; // Expression already correct type!
159159
169169 // We also do not allow conversion of a cast that casts from a ptr to array
170170 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
171171 //
172 if (const PointerType *SPT =
172 if (const PointerType *SPT =
173173 dyn_cast(I->getOperand(0)->getType()))
174174 if (const PointerType *DPT = dyn_cast(I->getType()))
175175 if (const ArrayType *AT = dyn_cast(SPT->getElementType()))
199199 if (!ExpressionConvertibleToType(LI->getPointerOperand(),
200200 PointerType::get(Ty), CTMap, TD))
201201 return false;
202 break;
202 break;
203203 }
204204 case Instruction::PHI: {
205205 PHINode *PN = cast(I);
226226 // %t2 = cast %List * * %t1 to %List *
227227 // into
228228 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
229 //
229 //
230230 GetElementPtrInst *GEP = cast(I);
231231 const PointerType *PTy = dyn_cast(Ty);
232232 if (!PTy) return false; // GEP must always return a pointer...
282282 // and want to convert it into something like this:
283283 // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
284284 //
285 if (GEP->getNumOperands() == 2 &&
285 if (GEP->getNumOperands() == 2 &&
286286 PTy->getElementType()->isSized() &&
287 TD.getTypeSize(PTy->getElementType()) ==
287 TD.getTypeSize(PTy->getElementType()) ==
288288 TD.getTypeSize(GEP->getType()->getElementType())) {
289289 const PointerType *NewSrcTy = PointerType::get(PVTy);
290290 if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
328328 }
329329
330330
331 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
331 Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
332332 ValueMapCache &VMC, const TargetData &TD) {
333333 if (V->getType() == Ty) return V; // Already where we need to be?
334334
363363 Instruction *Res; // Result of conversion
364364
365365 ValueHandle IHandle(VMC, I); // Prevent I from being removed!
366
366
367367 Constant *Dummy = Constant::getNullValue(Ty);
368368
369369 switch (I->getOpcode()) {
372372 Res = new CastInst(I->getOperand(0), Ty, Name);
373373 VMC.NewCasts.insert(ValueHandle(VMC, Res));
374374 break;
375
375
376376 case Instruction::Add:
377377 case Instruction::Sub:
378378 Res = BinaryOperator::create(cast(I)->getOpcode(),
435435 // %t2 = cast %List * * %t1 to %List *
436436 // into
437437 // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
438 //
438 //
439439 GetElementPtrInst *GEP = cast(I);
440440
441441 // Check to see if there are zero elements that we can remove from the
460460
461461 if (Res == 0 && GEP->getNumOperands() == 2 &&
462462 GEP->getType() == PointerType::get(Type::SByteTy)) {
463
463
464464 // Otherwise, we can convert a GEP from one form to the other iff the
465465 // current gep is of the form 'getelementptr sbyte*, unsigned N
466466 // and we could convert this to an appropriate GEP for the new type.
474474 std::vector Indices;
475475 const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
476476 Indices, TD, &It);
477 if (ElTy) {
477 if (ElTy) {
478478 assert(ElTy == PVTy && "Internal error, setup wrong!");
479479 Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
480480 Indices, Name);
624624 // We also do not allow conversion of a cast that casts from a ptr to array
625625 // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
626626 //
627 if (const PointerType *SPT =
627 if (const PointerType *SPT =
628628 dyn_cast(I->getOperand(0)->getType()))
629629 if (const PointerType *DPT = dyn_cast(I->getType()))
630630 if (const ArrayType *AT = dyn_cast(SPT->getElementType()))
644644 CTMap[I] = RetTy;
645645 return true;
646646 }
647 // We have to return failure here because ValueConvertibleToType could
647 // We have to return failure here because ValueConvertibleToType could
648648 // have polluted our map
649649 return false;
650650 }
680680
681681 if (const PointerType *PT = dyn_cast(Ty)) {
682682 LoadInst *LI = cast(I);
683
683
684684 const Type *LoadedTy = PT->getElementType();
685685
686686 // They could be loading the first element of a composite type...
732732 assert(Offset == 0 && "Offset changed!");
733733 if (ElTy == 0) // Element at offset zero in struct doesn't exist!
734734 return false; // Can only happen for {}*
735
735
736736 if (ElTy == Ty) // Looks like the 0th element of structure is
737737 return true; // compatible! Accept now!
738738
762762 }
763763
764764 // Must move the same amount of data...
765 if (!ElTy->isSized() ||
765 if (!ElTy->isSized() ||
766766 TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
767767 return false;
768768
800800 CST = ConstantSInt::get(Index->getType(), DataSize);
801801 else
802802 CST = ConstantUInt::get(Index->getType(), DataSize);
803
803
804804 TempScale = BinaryOperator::create(Instruction::Mul, Index, CST);
805805 Index = TempScale;
806806 }
853853 // the call provides...
854854 //
855855 if (NumArgs < FTy->getNumParams()) return false;
856
856
857857 // Unless this is a vararg function type, we cannot provide more arguments
858858 // than are desired...
859859 //
877877 //
878878 return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
879879 }
880
880
881881 const PointerType *MPtr = cast(I->getOperand(0)->getType());
882882 const FunctionType *FTy = cast(MPtr->getElementType());
883883 if (!FTy->isVarArg()) return false;
940940 ValueHandle IHandle(VMC, I);
941941
942942 const Type *NewTy = NewVal->getType();
943 Constant *Dummy = (NewTy != Type::VoidTy) ?
943 Constant *Dummy = (NewTy != Type::VoidTy) ?
944944 Constant::getNullValue(NewTy) : 0;
945945
946946 switch (I->getOpcode()) {
10241024 Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
10251025 }
10261026 }
1027
1027
10281028 Res = new LoadInst(Src, Name);
10291029 assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
10301030 break;
10411041 //
10421042 const Type *ElTy =
10431043 cast(VMCI->second->getType())->getElementType();
1044
1044
10451045 Value *SrcPtr = VMCI->second;
10461046
10471047 if (ElTy != NewTy) {
10481048 // We check that this is a struct in the initial scan...
10491049 const StructType *SElTy = cast(ElTy);
1050
1050
10511051 std::vector Indices;
10521052 Indices.push_back(Constant::getNullValue(Type::UIntTy));
10531053
11341134 // anything that is a pointer type...
11351135 //
11361136 BasicBlock::iterator It = I;
1137
1137
11381138 // Check to see if the second argument is an expression that can
11391139 // be converted to the appropriate size... if so, allow it.
11401140 //
11421142 const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
11431143 Indices, TD, &It);
11441144 assert(ElTy != 0 && "GEP Conversion Failure!");
1145
1145
11461146 Res = new GetElementPtrInst(NewVal, Indices, Name);
11471147 } else {
11481148 // Convert a getelementptr ulong * %reg123, uint %N
12701270
12711271 //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
12721272
1273 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
1273 for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
12741274 OI != OE; ++OI)
12751275 if (Instruction *U = dyn_cast(OI)) {
12761276 *OI = 0;
0 //===- Hello.cpp - Example code from "Writing an LLVM Pass" ---------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements two versions of the LLVM "Hello World" pass described
2323 std::cerr << "Hello: " << F.getName() << "\n";
2424 return false;
2525 }
26 };
26 };
2727 RegisterOpt X("hello", "Hello World Pass");
2828
2929 // Hello2 - The second implementation with getAnalysisUsage implemented.
3737 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
3838 AU.setPreservesAll();
3939 };
40 };
40 };
4141 RegisterOpt Y("hello2", "Hello World Pass (with getAnalysisUsage implemented)");
4242 }
0 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass promotes "by reference" arguments to be "by value" arguments. In
6666 virtual bool runOnSCC(const std::vector &SCC);
6767 private:
6868 bool PromoteArguments(CallGraphNode *CGN);
69 bool isSafeToPromoteArgument(Argument *Arg) const;
69 bool isSafeToPromoteArgument(Argument *Arg) const;
7070 Function *DoPromotion(Function *F, std::vector &ArgsToPromote);
7171 };
7272
8888 LocalChange |= PromoteArguments(SCC[i]);
8989 Changed |= LocalChange; // Remember that we changed something.
9090 } while (LocalChange);
91
91
9292 return Changed;
9393 }
9494
305305 unsigned idx = 0;
306306 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
307307 if (LHS[idx] != RHS[idx]) {
308 return cast(LHS[idx])->getRawValue() <
308 return cast(LHS[idx])->getRawValue() <
309309 cast(RHS[idx])->getRawValue();
310310 }
311311 }
324324 Function *ArgPromotion::DoPromotion(Function *F,
325325 std::vector &Args2Prom) {
326326 std::set ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
327
327
328328 // Start by computing a new prototype for the function, which is the same as
329329 // the old function, but has modified arguments.
330330 const FunctionType *FTy = F->getFunctionType();
390390 Params.push_back(Type::IntTy);
391391 }
392392 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
393
393
394394 // Create the new function body and insert it into the module...
395395 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
396396 F->getParent()->getFunctionList().insert(F, NF);
455455 Call->setName("");
456456 New->setName(Name);
457457 }
458
458
459459 // Finally, remove the old call from the program, reducing the use-count of
460460 // F.
461461 Call->getParent()->getInstList().erase(Call);
0 //===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines the interface to a pass that merges duplicate global
5959 // Only process constants with initializers
6060 if (GV->isConstant() && GV->hasInitializer()) {
6161 Constant *Init = GV->getInitializer();
62
62
6363 // Check to see if the initializer is already known...
6464 std::map::iterator I = CMap.find(Init);
65
65
6666 if (I == CMap.end()) { // Nope, add it to the map
6767 CMap.insert(I, std::make_pair(Init, GV));
6868 } else if (GV->hasInternalLinkage()) { // Yup, this is a duplicate!
7474 I->second = GV;
7575 }
7676 }
77
77
7878 if (Replacements.empty())
7979 return MadeChange;
8080 CMap.clear();
81
81
8282 // Now that we have figured out which replacements must be made, do them all
8383 // now. This avoid invalidating the pointers in CMap, which are unneeded
8484 // now.
8585 for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
8686 // Eliminate any uses of the dead global...
8787 Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
88
88
8989 // Delete the global value from the module...
9090 M.getGlobalList().erase(Replacements[i].first);
9191 }
92
92
9393 NumMerged += Replacements.size();
9494 Replacements.clear();
9595 }
0 //===-- DeadArgumentElimination.cpp - Eliminate dead arguments ------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass deletes dead arguments from internal functions. Dead argument
8787 void MarkArgumentLive(Argument *Arg);
8888 void MarkRetValLive(Function *F);
8989 void MarkReturnInstArgumentLive(ReturnInst *RI);
90
90
9191 void RemoveDeadArgumentsFromFunction(Function *F);
9292 };
9393 RegisterOpt X("deadargelim", "Dead Argument Elimination");
167167 if (!F.hasInternalLinkage() &&
168168 (!ShouldHackArguments() || F.getIntrinsicID()))
169169 FunctionIntrinsicallyLive = true;
170 else
170 else
171171 for (Value::use_iterator I = F.use_begin(), E = F.use_end(); I != E; ++I) {
172172 // If this use is anything other than a call site, the function is alive.
173173 CallSite CS = CallSite::get(*I);
196196 RetValLiveness = Live;
197197 break;
198198 }
199
199
200200 // If the function is PASSED IN as an argument, its address has been taken
201201 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
202202 AI != E; ++AI)
299299 void DAE::MarkArgumentLive(Argument *Arg) {
300300 std::set::iterator It = MaybeLiveArguments.lower_bound(Arg);
301301 if (It == MaybeLiveArguments.end() || *It != Arg) return;
302
302
303303 DEBUG(std::cerr << " MaybeLive argument now live: " << Arg->getName()<<"\n");
304304 MaybeLiveArguments.erase(It);
305305 LiveArguments.insert(Arg);
306
306
307307 // Loop over all of the call sites of the function, making any arguments
308308 // passed in to provide a value for this argument live as necessary.
309309 //
439439 New->setName(Name);
440440 }
441441 }
442
442
443443 // Finally, remove the old call from the program, reducing the use-count of
444444 // F.
445445 Call->getParent()->getInstList().erase(Call);
498498 while (!InstructionsToInspect.empty()) {
499499 Instruction *I = InstructionsToInspect.back();
500500 InstructionsToInspect.pop_back();
501
501
502502 if (ReturnInst *RI = dyn_cast(I)) {
503503 // For return instructions, we just have to check to see if the return
504504 // value for the current function is known now to be alive. If so, any
512512 assert(CS.getInstruction() && "Unknown instruction for the I2I list!");
513513
514514 Function *Callee = CS.getCalledFunction();
515
515
516516 // If we found a call or invoke instruction on this list, that means that
517517 // an argument of the function is a call instruction. If the argument is
518518 // live, then the return value of the called instruction is now live.
555555 if (MaybeLiveArguments.empty() && DeadArguments.empty() &&
556556 MaybeLiveRetVal.empty() && DeadRetVal.empty())
557557 return false;
558
558
559559 // Otherwise, compact into one set, and start eliminating the arguments from
560560 // the functions.
561561 DeadArguments.insert(MaybeLiveArguments.begin(), MaybeLiveArguments.end());
0 //===- DeadTypeElimination.cpp - Eliminate unused types for symbol table --===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass is used to cleanup the output of GCC. It eliminate names for types
0 //===-- ExtractFunction.cpp - Function extraction pass --------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass extracts
2424 /// specified function. Otherwise, it deletes as much of the module as
2525 /// possible, except for the function specified.
2626 ///
27 FunctionExtractorPass(Function *F = 0, bool deleteFn = true)
27 FunctionExtractorPass(Function *F = 0, bool deleteFn = true)
2828 : Named(F), deleteFunc(deleteFn) {}
2929
3030 bool runOnModule(Module &M) {
3535
3636 if (deleteFunc)
3737 return deleteFunction();
38 else
38 else
3939 return isolateFunction(M);
4040 }
4141
5656 I->setInitializer(0); // Make all variables external
5757 I->setLinkage(GlobalValue::ExternalLinkage);
5858 }
59
59
6060 // All of the functions may be used by global variables or the named
6161 // function. Loop through them and create a new, external functions that
6262 // can be "used", instead of ones with bodies.
6363 std::vector NewFunctions;
64
64
6565 Function *Last = --M.end(); // Figure out where the last real fn is.
66
66
6767 for (Module::iterator I = M.begin(); ; ++I) {
6868 if (&*I != Named) {
6969 Function *New = new Function(I->getFunctionType(),
7070 GlobalValue::ExternalLinkage,
7171 I->getName());
7272 I->setName(""); // Remove Old name
73
73
7474 // If it's not the named function, delete the body of the function
7575 I->dropAllReferences();
76
76
7777 M.getFunctionList().push_back(New);
7878 NewFunctions.push_back(New);
7979 }
80
80
8181 if (&*I == Last) break; // Stop after processing the last function
8282 }
83
83
8484 // Now that we have replacements all set up, loop through the module,
8585 // deleting the old functions, replacing them with the newly created
8686 // functions.
9191 if (&*I != Named) {
9292 // Make everything that uses the old function use the new dummy fn
9393 I->replaceAllUsesWith(NewFunctions[FuncNum++]);
94
94
9595 Function *Old = I;
9696 ++I; // Move the iterator to the new function
97
97
9898 // Delete the old function!
9999 M.getFunctionList().erase(Old);
100
100
101101 } else {
102102 ++I; // Skip the function we are extracting
103103 }
104104 } while (&*I != NewFunctions[0]);
105105 }
106
106
107107 return true;
108108 }
109109 };
0 //===- FunctionResolution.cpp - Resolve declarations to implementations ---===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // Loop over the functions that are in the module and look for functions that
5656 Function *Old = cast(Globals[i]);
5757 const FunctionType *OldMT = Old->getFunctionType();
5858 const FunctionType *ConcreteMT = Concrete->getFunctionType();
59
59
6060 if (OldMT->getNumParams() > ConcreteMT->getNumParams() &&
6161 !ConcreteMT->isVarArg())
6262 if (!Old->use_empty()) {
6868 WriteAsOperand(std::cerr, Concrete);
6969 std::cerr << "\n";
7070 }
71
71
7272 // Check to make sure that if there are specified types, that they
7373 // match...
7474 //
7878 if (!Old->use_empty() && !Concrete->use_empty())
7979 for (unsigned i = 0; i < NumArguments; ++i)
8080 if (OldMT->getParamType(i) != ConcreteMT->getParamType(i))
81 if (OldMT->getParamType(i)->getTypeID() !=
81 if (OldMT->getParamType(i)->getTypeID() !=
8282 ConcreteMT->getParamType(i)->getTypeID()) {
8383 std::cerr << "WARNING: Function [" << Old->getName()
8484 << "]: Parameter types conflict for: '";
8888 std::cerr << "'\n";
8989 return Changed;
9090 }
91
91
9292 // Attempt to convert all of the uses of the old function to the concrete
9393 // form of the function. If there is a use of the fn that we don't
9494 // understand here we punt to avoid making a bad transformation.
173173 if (!F->isExternal()) {
174174 if (Concrete && !Concrete->isExternal())
175175 return false; // Found two different functions types. Can't choose!
176
176
177177 Concrete = Globals[i];
178178 } else if (Concrete) {
179179 if (Concrete->isExternal()) // If we have multiple external symbols...
180 if (F->getFunctionType()->getNumParams() >
180 if (F->getFunctionType()->getNumParams() >
181181 cast(Concrete)->getFunctionType()->getNumParams())
182182 Concrete = F; // We are more concrete than "Concrete"!
183183
212212 else if (!Globals[i]->hasInternalLinkage())
213213 NumInstancesWithExternalLinkage++;
214214 }
215
215
216216 if (!HasExternal && NumInstancesWithExternalLinkage <= 1)
217217 return false; // Nothing to do? Must have multiple internal definitions.
218218
230230 OtherF->getFunctionType()->isVarArg() &&
231231 OtherF->getFunctionType()->getNumParams() == 0)
232232 DontPrintWarning = true;
233
233
234234 // Otherwise, if the non-concrete global is a global array variable with a
235235 // size of 0, and the concrete global is an array with a real size, don't
236236 // warn. This occurs due to declaring 'extern int A[];'.
0 //===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This transform is designed to eliminate unreachable internal globals from the
110110 NumVariables += DeadGlobalVars.size();
111111 Changed = true;
112112 }
113
113
114114 // Make sure that all memory is released
115115 AliveGlobals.clear();
116116 return Changed;
147147 if (GlobalValue *GV = dyn_cast(*U))
148148 GlobalIsNeeded(GV);
149149 else if (Constant *C = dyn_cast(*U))
150 MarkUsedGlobalsAsNeeded(C);
150 MarkUsedGlobalsAsNeeded(C);
151151 }
152152 }
153153
173173 GV.removeDeadConstantUsers();
174174 return GV.use_empty();
175175 }
176
176
177177 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
178178 // by constants itself. Note that constants cannot be cyclic, so this test is
179179 // pretty easy to implement recursively.
0 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass transforms simple global variables that never have their address
4646 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
4747 AU.addRequired();
4848 }
49
49
5050 bool runOnModule(Module &M);
5151
5252 private:
200200 // If the first two indices are constants, this can be SRA'd.
201201 if (isa(I->getOperand(0))) {
202202 if (I->getNumOperands() < 3 || !isa(I->getOperand(1)) ||
203 !cast(I->getOperand(1))->isNullValue() ||
203 !cast(I->getOperand(1))->isNullValue() ||
204204 !isa(I->getOperand(2)))
205205 GS.isNotSuitableForSRA = true;
206206 } else if (ConstantExpr *CE = dyn_cast(I->getOperand(0))){
303303 bool Changed = false;
304304 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
305305 User *U = *UI++;
306
306
307307 if (LoadInst *LI = dyn_cast(U)) {
308308 if (Init) {
309309 // Replace the load with the initializer.
366366 assert(GV->hasInternalLinkage() && !GV->isConstant());
367367 Constant *Init = GV->getInitializer();
368368 const Type *Ty = Init->getType();
369
369
370370 std::vector NewGlobals;
371371 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
372372
421421 assert(((isa(GEP) &&
422422 cast(GEP)->getOpcode()==Instruction::GetElementPtr)||
423423 isa(GEP)) && "NonGEP CE's are not SRAable!");
424
424
425425 // Ignore the 1th operand, which has to be zero or else the program is quite
426426 // broken (undefined). Get the 2nd operand, which is the structure or array
427427 // index.
498498 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
499499 } else if (GetElementPtrInst *GEPI = dyn_cast(*UI)) {
500500 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
501 } else if (isa(*UI) &&
501 } else if (isa(*UI) &&
502502 isa(UI->getOperand(1))) {
503503 // Ignore setcc X, null
504504 } else {
680680 MI->eraseFromParent();
681681 MI = NewMI;
682682 }
683
683
684684 // Create the new global variable. The contents of the malloc'd memory is
685685 // undefined, so initialize with an undef value.
686686 Constant *Init = UndefValue::get(MI->getAllocatedType());
688688 GlobalValue::InternalLinkage, Init,
689689 GV->getName()+".body");
690690 GV->getParent()->getGlobalList().insert(GV, NewGV);
691
691
692692 // Anything that used the malloc now uses the global directly.
693693 MI->replaceAllUsesWith(NewGV);
694694
698698
699699 // If there is a comparison against null, we will insert a global bool to
700700 // keep track of whether the global was initialized yet or not.
701 GlobalVariable *InitBool =
702 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
701 GlobalVariable *InitBool =
702 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
703703 ConstantBool::False, GV->getName()+".init");
704704 bool InitBoolUsed = false;
705705
816816 if (Constant *SOVC = dyn_cast(StoredOnceVal)) {
817817 if (GV->getInitializer()->getType() != SOVC->getType())
818818 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
819
819
820820 // Optimize away any trapping uses of the loaded value.
821821 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
822822 return true;
845845 }
846846
847847 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
848 /// values ever stored into GV are its initializer and OtherVal.
848 /// values ever stored into GV are its initializer and OtherVal.
849849 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
850850 // Create the new global, initializing it to false.
851851 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
894894 } else if (!UI->use_empty()) {
895895 // Change the load into a load of bool then a select.
896896 LoadInst *LI = cast(UI);
897
897
898898 std::string Name = LI->getName(); LI->setName("");
899899 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
900900 Value *NSI;
901901 if (IsOneZero)
902902 NSI = new CastInst(NLI, LI->getType(), Name, LI);
903 else
903 else
904904 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
905905 LI->replaceAllUsesWith(NSI);
906906 }
946946 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
947947 if (!isa(GV->getInitializer()))
948948 new StoreInst(GV->getInitializer(), Alloca, FirstI);
949
949
950950 GV->replaceAllUsesWith(Alloca);
951951 GV->eraseFromParent();
952952 ++NumLocalized;
968968 Changed = true;
969969 }
970970 return Changed;
971
971
972972 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
973973 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
974974 GV->setConstant(true);
975
975
976976 // Clean up any obviously simplifiable users now.
977977 CleanupConstantGlobalUsers(GV, GV->getInitializer());
978
978
979979 // If the global is dead now, just nuke it.
980980 if (GV->use_empty()) {
981981 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
983983 GV->eraseFromParent();
984984 ++NumDeleted;
985985 }
986
986
987987 ++NumMarked;
988988 return true;
989989 } else if (!GS.isNotSuitableForSRA &&
10011001 if (isa(GV->getInitializer())) {
10021002 // Change the initial value here.
10031003 GV->setInitializer(SOVConstant);
1004
1004
10051005 // Clean up any obviously simplifiable users now.
10061006 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1007
1007
10081008 if (GV->use_empty()) {
10091009 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
10101010 "simplify all users and delete global!\n");
0 //===-- IPConstantPropagation.cpp - Propagate constants through calls -----===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass implements an _extremely_ simple interprocedural constant
8080 return false; // Used by a non-instruction, do not transform
8181 else {
8282 CallSite CS = CallSite::get(cast(*I));
83 if (CS.getInstruction() == 0 ||
83 if (CS.getInstruction() == 0 ||
8484 CS.getCalledFunction() != &F)
8585 return false; // Not a direct call site?
86
86
8787 // Check out all of the potentially constant arguments
8888 CallSite::arg_iterator AI = CS.arg_begin();
8989 Function::arg_iterator Arg = F.arg_begin();
162162 ReplacedAllUsers = false;
163163 else {
164164 CallSite CS = CallSite::get(cast(*I));
165 if (CS.getInstruction() == 0 ||
165 if (CS.getInstruction() == 0 ||
166166 CS.getCalledFunction() != &F) {
167167 ReplacedAllUsers = false;
168168 } else {
0 //===- InlineSimple.cpp - Code to perform simple function inlining --------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements bottom-up inlining of functions into callees.
100100 if (AllOperandsConstant) {
101101 // We will get to remove this instruction...
102102 Reduction += 7;
103
103
104104 // And any other instructions that use it which become constants
105105 // themselves.
106106 Reduction += CountCodeReductionForConstant(&Inst);
0 //===- Inliner.cpp - Code common to all inliners --------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the mechanics required to implement inlining without
5252 for (CallGraphNode::iterator I = CalleeNode->begin(),
5353 E = CalleeNode->end(); I != E; ++I)
5454 CallerNode->addCalledFunction(*I);
55
55
5656 // If we inlined the last possible call site to the function, delete the
5757 // function body now.
5858 if (Callee->use_empty() && Callee->hasInternalLinkage() &&
5959 !SCCFunctions.count(Callee)) {
6060 DEBUG(std::cerr << " -> Deleting dead function: "
6161 << Callee->getName() << "\n");
62
62
6363 // Remove any call graph edges from the callee to its callees.
6464 while (CalleeNode->begin() != CalleeNode->end())
6565 CalleeNode->removeCallEdgeTo(*(CalleeNode->end()-1));
66
66
6767 // Removing the node for callee from the call graph and delete it.
6868 delete CG.removeFunctionFromModule(CalleeNode);
6969 ++NumDeleted;
9898 }
9999
100100 DEBUG(std::cerr << ": " << CallSites.size() << " call sites.\n");
101
101
102102 // Now that we have all of the call sites, move the ones to functions in the
103103 // current SCC to the end of the list.
104104 unsigned FirstCallInSCC = CallSites.size();
106106 if (Function *F = CallSites[i].getCalledFunction())
107107 if (SCCFunctions.count(F))
108108 std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
109
109
110110 // Now that we have all of the call sites, loop over them and inline them if
111111 // it looks profitable to do so.
112112 bool Changed = false;
136136 } else {
137137 DEBUG(std::cerr << " Inlining: cost=" << InlineCost
138138 << ", Call: " << *CS.getInstruction());
139
139
140140 Function *Caller = CS.getInstruction()->getParent()->getParent();
141141
142142 // Attempt to inline the function...
177177 // Remove any call graph edges from the function to its callees.
178178 while (CGN->begin() != CGN->end())
179179 CGN->removeCallEdgeTo(*(CGN->end()-1));
180
180
181181 // Remove any edges from the external node to the function's call graph
182182 // node. These edges might have been made irrelegant due to
183183 // optimization of the program.
184184 CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
185
185
186186 // Removing the node for callee from the call graph and delete it.
187187 FunctionsToRemove.insert(CGN);
188188 }
0 //===- InlineCommon.h - Code common to all inliners -------------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines a simple policy-based bottom-up inliner. This file
0 //===-- Internalize.cpp - Mark functions internal -------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass loops over all of the functions in the input module, looking for a
3737 APIList("internalize-public-api-list", cl::value_desc("list"),
3838 cl::desc("A list of symbol names to preserve"),
3939 cl::CommaSeparated);
40
40
4141 class InternalizePass : public ModulePass {
4242 std::set ExternalNames;
4343 public:
7979 }
8080
8181 bool Changed = false;
82
82
8383 // Found a main function, mark all functions not named main as internal.
8484 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
8585 if (!I->isExternal() && // Function must be defined here
108108 ++NumGlobals;
109109 DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n");
110110 }
111
111
112112 return Changed;
113113 }
114114 };
0 //===- LoopExtractor.cpp - Extract each loop into a new function ----------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // A pass wrapper around the ExtractLoop() scalar transformation to extract each
2626
2727 namespace {
2828 Statistic<> NumExtracted("loop-extract", "Number of loops extracted");
29
29
3030 // FIXME: This is not a function pass, but the PassManager doesn't allow
3131 // Module passes to require FunctionPasses, so we can't get loop info if we're
3232 // not a function pass.
3636 LoopExtractor(unsigned numLoops = ~0) : NumLoops(numLoops) {}
3737
3838 virtual bool runOnFunction(Function &F);
39
39
4040 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
4141 AU.addRequiredID(BreakCriticalEdgesID);
4242 AU.addRequiredID(LoopSimplifyID);
4545 }
4646 };
4747
48 RegisterOpt
48 RegisterOpt
4949 X("loop-extract", "Extract loops into new functions");
5050
5151 /// SingleLoopExtractor - For bugpoint.
5353 SingleLoopExtractor() : LoopExtractor(1) {}
5454 };
5555
56 RegisterOpt
56 RegisterOpt
5757 Y("loop-extract-single", "Extract at most one loop into a new function");
58 } // End anonymous namespace
58 } // End anonymous namespace
5959
6060 // createLoopExtractorPass - This pass extracts all natural loops from the
6161 // program into a function if it can.
8686 // than a minimal wrapper around the loop, extract the loop.
8787 Loop *TLL = *LI.begin();
8888 bool ShouldExtractLoop = false;
89
89
9090 // Extract the loop if the entry block doesn't branch to the loop header.
9191 TerminatorInst *EntryTI = F.getEntryBlock().getTerminator();
9292 if (!isa(EntryTI) ||
93 !cast(EntryTI)->isUnconditional() ||
93 !cast(EntryTI)->isUnconditional() ||
9494 EntryTI->getSuccessor(0) != TLL->getHeader())
9595 ShouldExtractLoop = true;
9696 else {
104104 break;
105105 }
106106 }
107
107
108108 if (ShouldExtractLoop) {
109109 if (NumLoops == 0) return Changed;
110110 --NumLoops;
183183
184184 for (unsigned i = 0, e = BlocksToExtract.size(); i != e; ++i)
185185 ExtractBasicBlock(BlocksToExtract[i]);
186
186
187187 return !BlocksToExtract.empty();
188188 }
0 //===- LowerSetJmp.cpp - Code pertaining to lowering set/long jumps -------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements the lowering of setjmp and longjmp to use the
203203
204204 // void __llvm_sjljeh_init_setjmpmap(void**)
205205 InitSJMap = M.getOrInsertFunction("__llvm_sjljeh_init_setjmpmap",
206 Type::VoidTy, SBPPTy, 0);
206 Type::VoidTy, SBPPTy, 0);
207207 // void __llvm_sjljeh_destroy_setjmpmap(void**)
208208 DestroySJMap = M.getOrInsertFunction("__llvm_sjljeh_destroy_setjmpmap",
209209 Type::VoidTy, SBPPTy, 0);
385385 // instructions after the call.
386386 for (BasicBlock::iterator I = ++BasicBlock::iterator(Inst), E = ABlock->end();
387387 I != E; ++I)
388 InstrsAfterCall.insert(I);
388 InstrsAfterCall.insert(I);
389389
390390 for (BasicBlock::iterator II = ABlock->begin();
391391 II != BasicBlock::iterator(Inst); ++II)
459459 std::vector Params(CI.op_begin() + 1, CI.op_end());
460460 InvokeInst* II = new
461461 InvokeInst(CI.getCalledValue(), NewBB, PrelimBBMap[Func],
462 Params, CI.getName(), Term);
462 Params, CI.getName(), Term);
463463
464464 // Replace the old call inst with the invoke inst and remove the call.
465465 CI.replaceAllUsesWith(II);
0 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements a simple interprocedural pass which walks the
7676 SCCMightThrow = true;
7777 break;
7878 }
79
79
8080 } else {
8181 // Indirect call, it might throw.
8282 SCCMightThrow = true;
108108 std::vector(II->op_begin()+3,
109109 II->op_end()),
110110 Name, II);
111
111
112112 // Anything that used the value produced by the invoke instruction
113113 // now uses the value produced by the call instruction.
114114 II->replaceAllUsesWith(Call);
115115 II->getUnwindDest()->removePredecessor(II->getParent());
116
116
117117 // Insert a branch to the normal destination right before the
118118 // invoke.
119119 new BranchInst(II->getNormalDest(), II);
120
120
121121 // Finally, delete the invoke instruction!
122122 I->getInstList().pop_back();
123
123
124124 ++NumRemoved;
125125 MadeChange = true;
126126 }
127127 }
128128
129 return MadeChange;
129 return MadeChange;
130130 }
131131
0 //===- RaiseAllocations.cpp - Convert %malloc & %free calls to insts ------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file defines the RaiseAllocations pass which convert malloc and free
3232 Function *FreeFunc; // Initialized by doPassInitializationVirt
3333 public:
3434 RaiseAllocations() : MallocFunc(0), FreeFunc(0) {}
35
35
3636 // doPassInitialization - For the raise allocations pass, this finds a
3737 // declaration for malloc and free if they exist.
3838 //
3939 void doInitialization(Module &M);
40
40
4141 // run - This method does the actual work of converting instructions over.
4242 //
4343 bool runOnModule(Module &M);
4444 };
45
45
4646 RegisterOpt
4747 X("raiseallocs", "Raise allocations from calls to instructions");
4848 } // end anonymous namespace
133133 (CS.getCalledFunction() == MallocFunc ||
134134 std::find(EqPointers.begin(), EqPointers.end(),
135135 CS.getCalledValue()) != EqPointers.end())) {
136
136
137137 Value *Source = *CS.arg_begin();
138
138
139139 // If no prototype was provided for malloc, we may need to cast the
140140 // source size.
141141 if (Source->getType() != Type::UIntTy)
142142 Source = new CastInst(Source, Type::UIntTy, "MallocAmtCast", I);
143
143
144144 std::string Name(I->getName()); I->setName("");
145145 MallocInst *MI = new MallocInst(Type::SByteTy, Source, Name, I);
146146 I->replaceAllUsesWith(MI);
182182 (CS.getCalledFunction() == FreeFunc ||
183183 std::find(EqPointers.begin(), EqPointers.end(),
184184 CS.getCalledValue()) != EqPointers.end())) {
185
185
186186 // If no prototype was provided for free, we may need to cast the
187187 // source pointer. This should be really uncommon, but it's necessary
188188 // just in case we are dealing with weird code like this:
0 //===- StripSymbols.cpp - Strip symbols and debug info from a module ------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This file implements stripping symbols out of symbol tables.
1616 //
1717 // Notice that:
1818 // * This pass makes code much less readable, so it should only be used in
19 // situations where the 'strip' utility would be used (such as reducing
19 // situations where the 'strip' utility would be used (such as reducing
2020 // code size, and making it harder to reverse engineer code).
2121 //
2222 //===----------------------------------------------------------------------===//
6262 }
6363 else if (!isa(C))
6464 C->destroyConstant();
65
65
6666 // If the constant referenced anything, see if we can delete it as well.
6767 while (!Operands.empty()) {
6868 RemoveDeadConstant(Operands.back());
143143 RemoveDeadConstant(GV);
144144 }
145145
146 return true;
146 return true;
147147 }
0 //===- BlockProfiling.cpp - Insert counters for block profiling -----------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass instruments the specified program with counters for basic block or
5050 }
5151
5252 unsigned NumFunctions = 0;
53 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
53 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
5454 if (!I->isExternal())
5555 ++NumFunctions;
5656
6161
6262 // Instrument all of the functions...
6363 unsigned i = 0;
64 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
64 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
6565 if (!I->isExternal())
6666 // Insert counter at the start of the function
6767 IncrementCounterInBlock(I->begin(), i++, Counters);
9292 }
9393
9494 unsigned NumBlocks = 0;
95 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
95 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
9696 NumBlocks += I->size();
9797
9898 const Type *ATy = ArrayType::get(Type::UIntTy, NumBlocks);
102102
103103 // Instrument all of the blocks...
104104 unsigned i = 0;
105 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
105 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
106106 for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
107107 // Insert counter at the start of the block
108108 IncrementCounterInBlock(BB, i++, Counters);
0 //===- EdgeProfiling.cpp - Insert counters for edge profiling -------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This pass instruments the specified program with counters for edge profiling.
0 //===-- EmitFunctions.cpp - interface to insert instrumentation -----------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This inserts into the input module three new global constants containing
2626 #include "llvm/Transforms/Instrumentation.h"
2727 using namespace llvm;
2828
29 namespace llvm {
29 namespace llvm {
3030
3131 namespace {
3232 enum Color{
3434 GREY,
3535 BLACK
3636 };
37
37
3838 struct EmitFunctionTable : public ModulePass {
3939 bool runOnModule(Module &M);
4040 };
41
41
4242 RegisterOpt
4343 X("emitfuncs", "Emit a function table for the reoptimizer");
4444 }
4747 color[node] = GREY;
4848
4949 for(succ_iterator vl = succ_begin(node), ve = succ_end(node); vl != ve; ++vl){
50
51 BasicBlock *BB = *vl;
52
50
51 BasicBlock *BB = *vl;
52
5353 if(color[BB]!=GREY && color[BB]!=BLACK){
5454 if(!doDFS(BB, color)){
5555 return 0;
7474 // Per Module pass for inserting function table
7575 bool EmitFunctionTable::runOnModule(Module &M){
7676 std::vector vType;
77
77
7878 std::vector vConsts;
7979 std::vector sBCons;
8080
8282 for(Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
8383 if (!MI->isExternal()) {
8484 vType.push_back(MI->getType());
85
85
8686 //std::cerr<
8787
8888 vConsts.push_back(MI);
8989 sBCons.push_back(ConstantInt::get(Type::SByteTy, hasBackEdge(MI)));
90
90
9191 counter++;
9292 }
93
93
9494 StructType *sttype = StructType::get(vType);
9595 Constant *cstruct = ConstantStruct::get(sttype, vConsts);
9696
9797 GlobalVariable *gb = new GlobalVariable(cstruct->getType(), true,
98 GlobalValue::ExternalLinkage,
98 GlobalValue::ExternalLinkage,
9999 cstruct, "llvmFunctionTable");
100100 M.getGlobalList().push_back(gb);
101101
102 Constant *constArray = ConstantArray::get(ArrayType::get(Type::SByteTy,
102 Constant *constArray = ConstantArray::get(ArrayType::get(Type::SByteTy,
103103 sBCons.size()),
104104 sBCons);
105105
109109
110110 M.getGlobalList().push_back(funcArray);
111111
112 ConstantInt *cnst = ConstantSInt::get(Type::IntTy, counter);
113 GlobalVariable *fnCount = new GlobalVariable(Type::IntTy, true,
114 GlobalValue::ExternalLinkage,
112 ConstantInt *cnst = ConstantSInt::get(Type::IntTy, counter);
113 GlobalVariable *fnCount = new GlobalVariable(Type::IntTy, true,
114 GlobalValue::ExternalLinkage,
115115 cnst, "llvmFunctionCount");
116116 M.getGlobalList().push_back(fnCount);
117117 return true; // Always modifies program
0 //===-- CombineBranch.cpp -------------------------------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // Combine multiple back-edges going to the same sink into a single
3030
3131 void getBackEdgesVisit(BasicBlock *u,
3232 std::map &color,
33 std::map &d,
33 std::map &d,
3434 int &time,
3535 std::map &be);
3636 void removeRedundant(std::map &be);
3737 public:
3838 bool runOnFunction(Function &F);
3939 };
40
40
4141 RegisterOpt
4242 X("branch-combine", "Multiple backedges going to same target are merged");
4343 }
5252 ///
5353 void CombineBranches::getBackEdgesVisit(BasicBlock *u,
5454 std::map &color,
55 std::map &d,
55 std::map &d,
5656 int &time,
5757 std::map &be) {
58
58
5959 color[u]=GREY;
6060 time++;
6161 d[u]=time;
6565
6666 if(color[BB]!=GREY && color[BB]!=BLACK)
6767 getBackEdgesVisit(BB, color, d, time, be);
68
68
6969 //now checking for d and f vals
7070 else if(color[BB]==GREY){
7171 //so v is ancestor of u if time of u > time of v
8282 void CombineBranches::removeRedundant(std::map &be){
8383 std::vector toDelete;
8484 std::map seenBB;
85
86 for(std::map::iterator MI = be.begin(),
85
86 for(std::map::iterator MI = be.begin(),
8787 ME = be.end(); MI != ME; ++MI){
88
88
8989 if(seenBB[MI->second])
9090 continue;
91
91
9292 seenBB[MI->second] = 1;
9393
9494 std::vector sameTarget;
9595 sameTarget.clear();
96
97 for(std::map::iterator MMI = be.begin(),
96
97 for(std::map::iterator MMI = be.begin(),
9898 MME = be.end(); MMI != MME; ++MMI){
99
99
100100 if(MMI->first == MI->first)
101101 continue;
102
102
103103 if(MMI->second == MI->second)
104104 sameTarget.push_back(MMI->first);
105
105
106106 }
107
107
108108 //so more than one branch to same target
109109 if(sameTarget.size()){
110110
125125
126126 ti->setSuccessor(index, newBB);
127127
128 for(BasicBlock::iterator BB2Inst = MI->second->begin(),
128 for(BasicBlock::iterator BB2Inst = MI->second->begin(),
129129 BBend = MI->second->end(); BB2Inst != BBend; ++BB2Inst){
130
130
131131 if (PHINode *phiInst = dyn_cast(BB2Inst)){
132132 int bbIndex;
133133 bbIndex = phiInst->getBasicBlockIndex(*VBI);
177177 int time = 0;
178178 getBackEdgesVisit (F.begin (), color, d, time, be);
179179 removeRedundant (be);
180
180
181181 return true; // FIXME: assumes a modification was always made.
182182 }
183183
0 //===-- EdgeCode.cpp - generate LLVM instrumentation code -----------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
8 //It implements the class EdgeCode: which provides
8 //It implements the class EdgeCode: which provides
99 //support for inserting "appropriate" instrumentation at
1010 //designated points in the graph
1111 //
12 //It also has methods to insert initialization code in
12 //It also has methods to insert initialization code in
1313 //top block of cfg
1414 //===----------------------------------------------------------------------===//
1515
2828 namespace llvm {
2929
3030 static void getTriggerCode(Module *M, BasicBlock *BB, int MethNo, Value *pathNo,
31 Value *cnt, Instruction *rInst){
32
31 Value *cnt, Instruction *rInst){
32
3333 vector tmpVec;
3434 tmpVec.push_back(Constant::getNullValue(Type::LongTy));
3535 tmpVec.push_back(Constant::getNullValue(Type::LongTy));
3737 BB->getInstList().push_back(Idx);
3838
3939 const Type *PIntTy = PointerType::get(Type::IntTy);
40 Function *trigMeth = M->getOrInsertFunction("trigger", Type::VoidTy,
40 Function *trigMeth = M->getOrInsertFunction("trigger", Type::VoidTy,
4141 Type::IntTy, Type::IntTy,
4242 PIntTy, PIntTy, 0);
4343 assert(trigMeth && "trigger method could not be inserted!");
5757
5858 //get the code to be inserted on the edge
5959 //This is determined from cond (1-6)
60 void getEdgeCode::getCode(Instruction *rInst, Value *countInst,
61 Function *M, BasicBlock *BB,
60 void getEdgeCode::getCode(Instruction *rInst, Value *countInst,
61 Function *M, BasicBlock *BB,
6262 vector &retVec){
63
63
6464 //Instruction *InsertPos = BB->getInstList().begin();
65
65
6666 //now check for cdIn and cdOut
6767 //first put cdOut
6868 if(cdOut!=NULL){
6969 cdOut->getCode(rInst, countInst, M, BB, retVec);
7070 }
71
71
7272 if(cdIn!=NULL){
7373 cdIn->getCode(rInst, countInst, M, BB, retVec);
7474 }
9292 #endif
9393 break;
9494 }
95
95
9696 //r+=k
9797 case 3:{
9898 Instruction *ldInst = new LoadInst(rInst, "ti1");//, InsertPos);
115115 tmpVec.push_back(ConstantSInt::get(Type::LongTy, inc));
116116 Instruction *Idx = new GetElementPtrInst(countInst, tmpVec, "");//,
117117
118 //Instruction *Idx = new GetElementPtrInst(countInst,
118 //Instruction *Idx = new GetElementPtrInst(countInst,
119119 // vector(1,ConstantSInt::get(Type::LongTy, inc)),
120120 // "");//, InsertPos);
121121 BB->getInstList().push_back(Idx);
122122
123123 Instruction *ldInst=new LoadInst(Idx, "ti1");//, InsertPos);
124124 BB->getInstList().push_back(ldInst);
125
125
126126 Value *val = ConstantSInt::get(Type::IntTy, 1);
127127 //Instruction *addIn =
128128 Instruction *newCount =
129129 BinaryOperator::create(Instruction::Add, ldInst, val,"ti2");
130130 BB->getInstList().push_back(newCount);
131
131
132132
133133 #ifdef INSERT_STORE
134134 //Instruction *stInst=new StoreInst(addIn, Idx, InsertPos);
135135 Instruction *stInst=new StoreInst(newCount, Idx);//, InsertPos);
136136 BB->getInstList().push_back(stInst);
137137 #endif
138
138
139139 Value *trAddIndex = ConstantSInt::get(Type::IntTy,inc);
140140
141141 retVec.push_back(newCount);
142142 retVec.push_back(trAddIndex);
143143 //insert trigger
144 //getTriggerCode(M->getParent(), BB, MethNo,
144 //getTriggerCode(M->getParent(), BB, MethNo,
145145 // ConstantSInt::get(Type::IntTy,inc), newCount, triggerInst);
146146 //end trigger code
147147
151151
152152 //case: count[r+inc]++
153153 case 5:{
154
154
155155 //ti1=inc+r
156156 Instruction *ldIndex=new LoadInst(rInst, "ti1");//, InsertPos);
157157 BB->getInstList().push_back(ldIndex);
160160 Instruction *addIndex=BinaryOperator::
161161 create(Instruction::Add, ldIndex, val,"ti2");//, InsertPos);
162162 BB->getInstList().push_back(addIndex);
163
163
164164 //now load count[addIndex]
165 Instruction *castInst=new CastInst(addIndex,
165 Instruction *castInst=new CastInst(addIndex,
166166 Type::LongTy,"ctin");//, InsertPos);
167167 BB->getInstList().push_back(castInst);
168168
179179 Value *cons=ConstantSInt::get(Type::IntTy,1);
180180 //count[addIndex]++
181181 //std::cerr<<"Type ldInst:"<getType()<<"\t cons:"<getType()<<"\n";
182 Instruction *newCount = BinaryOperator::create(Instruction::Add, ldInst,
182 Instruction *newCount = BinaryOperator::create(Instruction::Add, ldInst,
183183 cons,"");
184184 BB->getInstList().push_back(newCount);
185
185
186186 #ifdef INSERT_STORE
187187 Instruction *stInst = new StoreInst(newCount, Idx);//, InsertPos);
188188 BB->getInstList().push_back(stInst);
212212 tmpVec.push_back(castInst2);
213213 Instruction *Idx = new GetElementPtrInst(countInst, tmpVec, "");//,
214214
215 //Instruction *Idx = new GetElementPtrInst(countInst,
215 //Instruction *Idx = new GetElementPtrInst(countInst,
216216 // vector(1,castInst2), "");
217
217
218218 BB->getInstList().push_back(Idx);
219
219
220220 Instruction *ldInst=new LoadInst(Idx, "ti2");//, InsertPos);
221221 BB->getInstList().push_back(ldInst);
222222
236236 retVec.push_back(ldIndex);
237237 break;
238238 }
239
239
240240 }
241241 }
242242
244244
245245 //Insert the initialization code in the top BB
246246 //this includes initializing r, and count
247 //r is like an accumulator, that
247 //r is like an accumulator, that
248248 //keeps on adding increments as we traverse along a path
249249 //and at the end of the path, r contains the path
250250 //number of that path
251251 //Count is an array, where Count[k] represents
252252 //the number of executions of path k
253 void insertInTopBB(BasicBlock *front,
254 int k,
253 void insertInTopBB(BasicBlock *front,
254 int k,
255255 Instruction *rVar, Value *threshold){
256 //rVar is variable r,
256 //rVar is variable r,
257257 //countVar is count[]
258258
259259 Value *Int0 = ConstantInt::get(Type::IntTy, 0);
260
260
261261 //now push all instructions in front of the BB
262262 BasicBlock::iterator here=front->begin();
263263 front->getInstList().insert(here, rVar);
264264 //front->getInstList().insert(here,countVar);
265
265
266266 //Initialize Count[...] with 0
267267
268268 //for (int i=0;i
280280 //insert a basic block with appropriate code
281281 //along a given edge
282282 void insertBB(Edge ed,
283 getEdgeCode *edgeCode,
284 Instruction *rInst,
285 Value *countInst,
283 getEdgeCode *edgeCode,
284 Instruction *rInst,
285 Value *countInst,
286286 int numPaths, int Methno, Value *threshold){
287287
288288 BasicBlock* BB1=ed.getFirst()->getElement();
289289 BasicBlock* BB2=ed.getSecond()->getElement();
290
290
291291 #ifdef DEBUG_PATH_PROFILES
292292 //debugging info
293293 cerr<<"Edges with codes ######################\n";
294294 cerr<getName()<<"->"<getName()<<"\n";
295295 cerr<<"########################\n";
296296 #endif
297
298 //We need to insert a BB between BB1 and BB2
297
298 //We need to insert a BB between BB1 and BB2
299299 TerminatorInst *TI=BB1->getTerminator();
300300 BasicBlock *newBB=new BasicBlock("counter", BB1->getParent());
301301
315315 else{
316316 if(BI->getSuccessor(0)==BB2)
317317 BI->setSuccessor(0, newBB);
318
318
319319 if(BI->getSuccessor(1)==BB2)
320320 BI->setSuccessor(1, newBB);
321321 }
323323 BasicBlock *triggerBB = NULL;
324324 if(retVec.size()>0){
325325 triggerBB = new BasicBlock("trigger", BB1->getParent());
326 getTriggerCode(BB1->getParent()->getParent(), triggerBB, Methno,
326 getTriggerCode(BB1->getParent()->getParent(), triggerBB, Methno,
327327 retVec[1], countInst, rInst);//retVec[0]);
328328
329329 //Instruction *castInst = new CastInst(retVec[0], Type::IntTy, "");
330330 Instruction *etr = new LoadInst(threshold, "threshold");
331
332 //std::cerr<<"type1: "<getType()<<" type2: "<getType()<<"\n";
333 Instruction *cmpInst = new SetCondInst(Instruction::SetLE, etr,
331
332 //std::cerr<<"type1: "<getType()<<" type2: "<getType()<<"\n";
333 Instruction *cmpInst = new SetCondInst(Instruction::SetLE, etr,
334334 retVec[0], "");
335335 Instruction *newBI2 = new BranchInst(triggerBB, BB2, cmpInst);
336336 //newBB->getInstList().push_back(castInst);
337337 newBB->getInstList().push_back(etr);
338338 newBB->getInstList().push_back(cmpInst);
339339 newBB->getInstList().push_back(newBI2);
340
340
341341 //triggerBB->getInstList().push_back(triggerInst);
342342 new BranchInst(BB2, 0, 0, triggerBB);
343343 }
346346 }
347347
348348 //now iterate over BB2, and set its Phi nodes right
349 for(BasicBlock::iterator BB2Inst = BB2->begin(), BBend = BB2->end();
349 for(BasicBlock::iterator BB2Inst = BB2->begin(), BBend = BB2->end();
350350 BB2Inst != BBend; ++BB2Inst){
351
351
352352 if(PHINode *phiInst=dyn_cast(BB2Inst)){
353353 int bbIndex=phiInst->getBasicBlockIndex(BB1);
354354 assert(bbIndex>=0);
0 //===-- Graph.cpp - Implements Graph class --------------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This implements Graph for helping in trace generation This graph gets used by
2222
2323 const graphListElement *findNodeInList(const Graph::nodeList &NL,
2424 Node *N) {
25 for(Graph::nodeList::const_iterator NI = NL.begin(), NE=NL.end(); NI != NE;
25 for(Graph::nodeList::const_iterator NI = NL.begin(), NE=NL.end(); NI != NE;
2626 ++NI)
2727 if (*NI->element== *N)
2828 return &*NI;
3737 }
3838
3939 //graph constructor with root and exit specified
40 Graph::Graph(std::vector n, std::vector e,
40 Graph::Graph(std::vector n, std::vector e,
4141 Node *rt, Node *lt){
4242 strt=rt;
4343 ext=lt;
4848 for(vector::iterator x=e.begin(), en=e.end(); x!=en; ++x){
4949 Edge ee=*x;
5050 int w=ee.getWeight();
51 //nodes[ee.getFirst()].push_front(graphListElement(ee.getSecond(),w, ee.getRandId()));
51 //nodes[ee.getFirst()].push_front(graphListElement(ee.getSecond(),w, ee.getRandId()));
5252 nodes[ee.getFirst()].push_back(graphListElement(ee.getSecond(),w, ee.getRandId()));
5353 }
54
54
5555 }
5656
5757 //sorting edgelist, called by backEdgeVist ONLY!!!
5858 Graph::nodeList &Graph::sortNodeList(Node *par, nodeList &nl, vector &be){
5959 assert(par && "null node pointer");
6060 BasicBlock *bbPar = par->getElement();
61
61
6262 if(nl.size()<=1) return nl;
6363 if(getExit() == par) return nl;
6464
7878
7979 assert(ti && "not a branch");
8080 assert(ti->getNumSuccessors()==2 && "less successors!");
81
81
8282 BasicBlock *tB = ti->getSuccessor(0);
8383 BasicBlock *fB = ti->getSuccessor(1);
8484 //so one of LI or min must be back edge!
108108 }
109109 }
110110 }
111
111
112112 else if (min->element->getElement() != LI->element->getElement()){
113113 TerminatorInst *tti = par->getElement()->getTerminator();
114114 BranchInst *ti = cast(tti);
115115 assert(ti && "not a branch");
116116
117117 if(ti->getNumSuccessors()<=1) continue;
118
118
119119 assert(ti->getNumSuccessors()==2 && "less successors!");
120
120
121121 BasicBlock *tB = ti->getSuccessor(0);
122122 BasicBlock *fB = ti->getSuccessor(1);
123
123
124124 if(tB == LI->element->getElement() || fB == min->element->getElement())
125125 min = LI;
126126 }
127127 }
128
128
129129 graphListElement tmpElmnt = *min;
130130 *min = *NLI;
131131 *NLI = tmpElmnt;
158158
159159 Node *nd2=ed.getSecond();
160160 nodeList &nli = nodes[ed.getFirst()];//getNodeList(ed.getFirst());
161
161
162162 for(nodeList::iterator NI=nli.begin(), NE=nli.end(); NI!=NE; ++NI)
163163 if(*NI->element == *nd2 && ed.getWeight()==NI->weight)
164164 return true;
165
165
166166 return false;
167167 }
168168
179179 }
180180
181181 //add an edge
182 //this adds an edge ONLY when
182 //this adds an edge ONLY when
183183 //the edge to be added does not already exist
184 //we "equate" two edges here only with their
184 //we "equate" two edges here only with their
185185 //end points
186186 void Graph::addEdge(Edge ed, int w){
187187 nodeList &ndList = nodes[ed.getFirst()];
189189
190190 if(findNodeInList(nodes[ed.getFirst()], nd2))
191191 return;
192
192
193193 //ndList.push_front(graphListElement(nd2,w, ed.getRandId()));
194194 ndList.push_back(graphListElement(nd2,w, ed.getRandId()));//chng
195195 //sortNodeList(ed.getFirst(), ndList);
295295 for(nodeMapTy::const_iterator EI=nodes.begin(), EE=nodes.end(); EI!=EE ;++EI){
296296 Node *lnode=EI->first;
297297 const nodeList &nl = getNodeList(lnode);
298 for(Graph::nodeList::const_iterator NI = nl.begin(), NE=nl.end(); NI != NE;
298 for(Graph::nodeList::const_iterator NI = nl.begin(), NE=nl.end(); NI != NE;
299299 ++NI)
300300 if (*NI->element== *nd)
301301 count++;
339339 //of the graph
340340 Graph* Graph::getMaxSpanningTree(){
341341 //assume connected graph
342
342
343343 Graph *st=new Graph();//max spanning tree, undirected edges
344344 int inf=9999999;//largest key
345345 vector lt = getAllNodes();
346
346
347347 //initially put all vertices in vector vt
348348 //assign wt(root)=0
349349 //wt(others)=infinity
350350 //
351351 //now:
352352 //pull out u: a vertex frm vt of min wt
353 //for all vertices w in vt,
354 //if wt(w) greater than
353 //for all vertices w in vt,
354 //if wt(w) greater than
355355 //the wt(u->w), then assign
356356 //wt(w) to be wt(u->w).
357357 //
359359 //keep pulling out vertices from vt till it is empty
360360
361361 vector vt;
362
362
363363 std::map parent;
364364 std::map ed_weight;
365365
372372 parent[thisNode]=NULL;
373373 ed_weight[thisNode]=0;
374374 }
375 else{
375 else{
376376 thisNode->setWeight(inf);
377377 }
378378 st->addNode(thisNode);//add all nodes to spanning tree
395395 }
396396
397397 //vt.erase(u);
398
398
399399 //remove u frm vt
400400 for(vector::iterator VI=vt.begin(), VE=vt.end(); VI!=VE; ++VI){
401401 if(**VI==*u){
403403 break;
404404 }
405405 }
406
406
407407 //assign wt(v) to all adjacent vertices v of u
408408 //only if v is in vt
409409 Graph::nodeList &nl = getNodeList(u);
437437 return st;
438438 }
439439
440 //print the graph (for debugging)
440 //print the graph (for debugging)
441441 void Graph::printGraph(){
442442 vector lt=getAllNodes();
443443 std::cerr<<"Graph---------------------\n";
468468 }
469469
470470 //a private method for doing DFS traversal of graph
471 //this is used in determining the reverse topological sort
471 //this is used in determining the reverse topological sort
472472 //of the graph
473473 void Graph::DFS_Visit(Node *nd, vector &toReturn){
474474 nd->setWeight(GREY);
481481 }
482482
483483 //Ordinarily, the graph is directional
484 //this converts the graph into an
484 //this converts the graph into an
485485 //undirectional graph
486486 //This is done by adding an edge
487487 //v->u for all existing edges u->v
488488 void Graph::makeUnDirectional(){
489489 vector allNodes=getAllNodes();
490 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
490 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
491491 ++NI) {
492492 nodeList &nl = getNodeList(*NI);
493493 for(nodeList::iterator NLI=nl.begin(), NLE=nl.end(); NLI!=NLE; ++NLI){
506506 //using min-spanning tree, and vice versa
507507 void Graph::reverseWts(){
508508 vector allNodes=getAllNodes();
509 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
509 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
510510 ++NI) {
511511 nodeList &node_list = getNodeList(*NI);
512 for(nodeList::iterator NLI=nodes[*NI].begin(), NLE=nodes[*NI].end();
512 for(nodeList::iterator NLI=nodes[*NI].begin(), NLE=nodes[*NI].end();
513513 NLI!=NLE; ++NLI)
514514 NLI->weight=-NLI->weight;
515515 }
534534 getBackEdgesVisit(getRoot(), be, color, d, time);
535535 }
536536
537 //helper function to get back edges: it is called by
537 //helper function to get back edges: it is called by
538538 //the "getBackEdges" function above
539539 void Graph::getBackEdgesVisit(Node *u, vector &be,
540540 std::map &color,
544544 d[u]=time;
545545
546546 vector &succ_list = getNodeList(u);
547
548 for(vector::iterator vl=succ_list.begin(),
547
548 for(vector::iterator vl=succ_list.begin(),
549549 ve=succ_list.end(); vl!=ve; ++vl){
550550 Node *v=vl->element;
551551 if(color[v]!=GREY && color[v]!=BLACK){
552552 getBackEdgesVisit(v, be, color, d, time);
553553 }
554
554
555555 //now checking for d and f vals
556556 if(color[v]==GREY){
557557 //so v is ancestor of u if time of u > time of v
0 //===-- Graph.h -------------------------------------------------*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // Header file for Graph: This Graph is used by PathProfiles class, and is used
5757 randId=rand();
5858 isnull=false;
5959 }
60
60
6161 inline Edge(Node *f,Node *s, int wt, double rd){
6262 first=f;
6363 second=s;
6464 weight=wt;
6565 randId=rd;
66 isnull=false;
66 isnull=false;
6767 }
6868
6969 inline Edge() { isnull = true; }
7272 inline Node* const getFirst() const { assert(!isNull()); return first; }
7373 inline Node* getSecond() { assert(!isNull()); return second; }
7474 inline Node* const getSecond() const { assert(!isNull()); return second; }
75
75
7676 inline int getWeight() { assert(!isNull()); return weight; }
7777 inline void setWeight(int n) { assert(!isNull()); weight=n; }
78
78
7979 inline void setFirst(Node *&f) { assert(!isNull()); first=f; }
8080 inline void setSecond(Node *&s) { assert(!isNull()); second=s; }
81
82
83 inline bool isNull() const { return isnull;}
84
81
82
83 inline bool isNull() const { return isnull;}
84
8585 inline bool operator<(const Edge& ed) const{
8686 // Can't be the same if one is null and the other isn't
8787 if (isNull() != ed.isNull())
8888 return true;
8989
90 return (*first<*(ed.getFirst()))||
90 return (*first<*(ed.getFirst()))||
9191 (*first==*(ed.getFirst()) && *second<*(ed.getSecond()));
9292 }
9393
9595 return !(*this
9696 }
9797
98 inline bool operator!=(const Edge& ed) const{return !(*this==ed);}
98 inline bool operator!=(const Edge& ed) const{return !(*this==ed);}
9999 };
100100
101101
102102 //graphListElement
103 //This forms the "adjacency list element" of a
103 //This forms the "adjacency list element" of a
104104 //vertex adjacency list in graph
105105 struct graphListElement{
106106 Node *element;
107107 int weight;
108108 double randId;
109 inline graphListElement(Node *n, int w, double rand){
110 element=n;
109 inline graphListElement(Node *n, int w, double rand){
110 element=n;
111111 weight=w;
112112 randId=rand;
113113 }
126126 return n1->getElement() < n2->getElement();
127127 }
128128 };
129
129
130130 template<>
131131 struct less : public binary_function {
132132 bool operator()(Edge e1, Edge e2) const {
133133 assert(!e1.isNull() && !e2.isNull());
134
134
135135 Node *x1=e1.getFirst();
136136 Node *x2=e1.getSecond();
137137 Node *y1=e2.getFirst();
209209 private:
210210 //the adjacency list of a vertex or node
211211 nodeMapTy nodes;
212
212
213213 //the start or root node
214214 Node *strt;
215215
217217 Node *ext;
218218
219219 //a private method for doing DFS traversal of graph
220 //this is used in determining the reverse topological sort
220 //this is used in determining the reverse topological sort
221221 //of the graph
222222 void DFS_Visit(Node *nd, std::vector &toReturn);
223223
231231 //have been visited
232232 //So we have a back edge when we meet a successor of
233233 //a node with smaller time, and GREY color
234 void getBackEdgesVisit(Node *u,
234 void getBackEdgesVisit(Node *u,
235235 std::vector &be,
236236 std::map &clr,
237 std::map &d,
237 std::map &d,
238238 int &time);
239239
240240 public:
247247
248248 //empty constructor: then add edges and nodes later on
249249 Graph() {}
250
250
251251 //constructor with root and exit node specified
252 Graph(std::vector n,
252 Graph(std::vector n,
253253 std::vector e, Node *rt, Node *lt);
254254
255255 //add a node
256256 void addNode(Node *nd);
257257
258258 //add an edge
259 //this adds an edge ONLY when
259 //this adds an edge ONLY when
260260 //the edge to be added doesn not already exist
261 //we "equate" two edges here only with their
261 //we "equate" two edges here only with their
262262 //end points
263263 void addEdge(Edge ed, int w);
264264
309309 //in r-topological sorted order
310310 //note that we assumed graph to be connected
311311 std::vector reverseTopologicalSort();
312
312
313313 //reverse the sign of weights on edges
314314 //this way, max-spanning tree could be obtained
315315 //usin min-spanning tree, and vice versa
316316 void reverseWts();
317317
318318 //Ordinarily, the graph is directional
319 //this converts the graph into an
319 //this converts the graph into an
320320 //undirectional graph
321321 //This is done by adding an edge
322322 //v->u for all existing edges u->v
324324
325325 //print graph: for debugging
326326 void printGraph();
327
327
328328 //get a vector of back edges in the graph
329329 void getBackEdges(std::vector &be, std::map &d);
330330
331331 nodeList &sortNodeList(Node *par, nodeList &nl, std::vector &be);
332
332
333333 //Get the Maximal spanning tree (also a graph)
334334 //of the graph
335335 Graph* getMaxSpanningTree();
336
336
337337 //get the nodeList adjacent to a node
338 //a nodeList element contains a node, and the weight
338 //a nodeList element contains a node, and the weight
339339 //corresponding to the edge for that element
340340 inline nodeList &getNodeList(Node *nd) {
341341 elementIterator nli = nodes.find(nd);
342342 assert(nli != nodes.end() && "Node must be in nodes map");
343343 return nodes[nd];//sortNodeList(nd, nli->second);
344344 }
345
345
346346 nodeList &getSortedNodeList(Node *nd, std::vector &be) {
347347 elementIterator nli = nodes.find(nd);
348348 assert(nli != nodes.end() && "Node must be in nodes map");
349349 return sortNodeList(nd, nodes[nd], be);
350350 }
351
351
352352 //get the root of the graph
353353 inline Node *getRoot() {return strt; }
354354 inline Node * const getRoot() const {return strt; }
364364 inline bool isLeaf(Node *n) const {return (*n==*ext); }
365365 };
366366
367 //This class is used to generate
367 //This class is used to generate
368368 //"appropriate" code to be inserted
369369 //along an edge
370370 //The code to be inserted can be of six different types
377377 //6: Count[r]++
378378 class getEdgeCode{
379379 private:
380 //cond implies which
380 //cond implies which
381381 //"kind" of code is to be inserted
382382 //(from 1-6 above)
383383 int cond;
384384 //inc is the increment: eg k, or 0
385385 int inc;
386
386
387387 //A backedge must carry the code
388388 //of both incoming "dummy" edge
389389 //and outgoing "dummy" edge
419419
420420 //set CdIn (only used for backedges)
421421 inline void setCdIn(getEdgeCode *gd){ cdIn=gd;}
422
422
423423 //set CdOut (only used for backedges)
424424 inline void setCdOut(getEdgeCode *gd){ cdOut=gd;}
425425
426426 //get the code to be inserted on the edge
427427 //This is determined from cond (1-6)
428 void getCode(Instruction *a, Value *b, Function *M, BasicBlock *BB,
428 void getCode(Instruction *a, Value *b, Function *M, BasicBlock *BB,
429429 std::vector &retVec);
430430 };
431431
432432
433433 //auxillary functions on graph
434434
435 //print a given edge in the form BB1Label->BB2Label
435 //print a given edge in the form BB1Label->BB2Label
436436 void printEdge(Edge ed);
437437
438 //Do graph processing: to determine minimal edge increments,
438 //Do graph processing: to determine minimal edge increments,
439439 //appropriate code insertions etc and insert the code at
440440 //appropriate locations
441441 void processGraph(Graph &g, Instruction *rInst, Value *countInst, std::vector &be, std::vector &stDummy, std::vector &exDummy, int n, int MethNo, Value *threshold);
451451
452452 //Insert the initialization code in the top BB
453453 //this includes initializing r, and count
454 //r is like an accumulator, that
454 //r is like an accumulator, that
455455 //keeps on adding increments as we traverse along a path
456456 //and at the end of the path, r contains the path
457457 //number of that path
469469 //such that if we traverse along any path from root to exit, and
470470 //add up the edge values, we get a path number that uniquely
471471 //refers to the path we travelled
472 int valueAssignmentToEdges(Graph& g, std::map nodePriority,
472 int valueAssignmentToEdges(Graph& g, std::map nodePriority,
473473 std::vector &be);
474474
475475 void getBBtrace(std::vector &vBB, int pathNo, Function *M);
0 //===- GraphAuxiliary.cpp - Auxiliary functions on graph ------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // auxiliary function associated with graph: they all operate on graph, and help
3535 //make sure the spanning tree is directional
3636 //iterate over ALL the edges of the graph
3737 vector allNodes=g.getAllNodes();
38 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
38 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
3939 ++NI){
4040 Graph::nodeList node_list=g.getNodeList(*NI);
41 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
41 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
4242 NLI!=NLE; ++NLI){
4343 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
4444 if(!(st.hasEdgeAndWt(f)))//addnl
5050 //Given a tree t, and a "directed graph" g
5151 //replace the edges in the tree t with edges that exist in graph
5252 //The tree is formed from "undirectional" copy of graph
53 //So whatever edges the tree has, the undirectional graph
54 //would have too. This function corrects some of the directions in
53 //So whatever edges the tree has, the undirectional graph
54 //would have too. This function corrects some of the directions in
5555 //the tree so that now, all edge directions in the tree match
5656 //the edge directions of corresponding edges in the directed graph
5757 static void removeTreeEdges(Graph &g, Graph& t){
5858 vector allNodes=t.getAllNodes();
59 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
59 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
6060 ++NI){
6161 Graph::nodeList nl=t.getNodeList(*NI);
6262 for(Graph::nodeList::iterator NLI=nl.begin(), NLE=nl.end(); NLI!=NLE;++NLI){
7171 //such that if we traverse along any path from root to exit, and
7272 //add up the edge values, we get a path number that uniquely
7373 //refers to the path we travelled
74 int valueAssignmentToEdges(Graph& g, map nodePriority,
74 int valueAssignmentToEdges(Graph& g, map nodePriority,
7575 vector &be){
7676 vector revtop=g.reverseTopologicalSort();
7777 map NumPaths;
78 for(vector::iterator RI=revtop.begin(), RE=revtop.end();
78 for(vector::iterator RI=revtop.begin(), RE=revtop.end();
7979 RI!=RE; ++RI){
8080 if(g.isLeaf(*RI))
8181 NumPaths[*RI]=1;
8686 Graph::nodeList &nlist=g.getSortedNodeList(*RI, be);
8787
8888 //sort nodelist by increasing order of numpaths
89
89
9090 int sz=nlist.size();
91
91
9292 for(int i=0;i
9393 int min=i;
9494 for(int j=i+1; j
9595 BasicBlock *bb1 = nlist[j].element->getElement();
9696 BasicBlock *bb2 = nlist[min].element->getElement();
97
97
9898 if(bb1 == bb2) continue;
99
99
100100 if(*RI == g.getRoot()){
101 assert(nodePriority[nlist[min].element]!=
102 nodePriority[nlist[j].element]
101 assert(nodePriority[nlist[min].element]!=
102 nodePriority[nlist[j].element]
103103 && "priorities can't be same!");
104
105 if(nodePriority[nlist[j].element] <
104
105 if(nodePriority[nlist[j].element] <
106106 nodePriority[nlist[min].element])
107 min = j;
107 min = j;
108108 }
109109
110110 else{
111111 TerminatorInst *tti = (*RI)->getElement()->getTerminator();
112
112
113113 BranchInst *ti = cast(tti);
114114 assert(ti && "not a branch");
115115 assert(ti->getNumSuccessors()==2 && "less successors!");
116
116
117117 BasicBlock *tB = ti->getSuccessor(0);
118118 BasicBlock *fB = ti->getSuccessor(1);
119
119
120120 if(tB == bb1 || fB == bb2)
121121 min = j;
122122 }
123
123
124124 }
125125 graphListElement tempEl=nlist[min];
126126 nlist[min]=nlist[i];
127127 nlist[i]=tempEl;
128128 }
129
129
130130 //sorted now!
131131 for(Graph::nodeList::iterator GLI=nlist.begin(), GLE=nlist.end();
132132 GLI!=GLE; ++GLI){
147147 //refers to the path we travelled
148148 //inc_Dir tells whether 2 edges are in same, or in different directions
149149 //if same direction, return 1, else -1
150 static int inc_Dir(Edge e, Edge f){
151 if(e.isNull())
150 static int inc_Dir(Edge e, Edge f){
151 if(e.isNull())
152152 return 1;
153
153
154154 //check that the edges must have at least one common endpoint
155155 assert(*(e.getFirst())==*(f.getFirst()) ||
156 *(e.getFirst())==*(f.getSecond()) ||
156 *(e.getFirst())==*(f.getSecond()) ||
157157 *(e.getSecond())==*(f.getFirst()) ||
158158 *(e.getSecond())==*(f.getSecond()));
159159
160 if(*(e.getFirst())==*(f.getSecond()) ||
160 if(*(e.getFirst())==*(f.getSecond()) ||
161161 *(e.getSecond())==*(f.getFirst()))
162162 return 1;
163
163
164164 return -1;
165165 }
166166
167167
168168 //used for getting edge increments (read comments above in inc_Dir)
169 //inc_DFS is a modification of DFS
170 static void inc_DFS(Graph& g,Graph& t,map& Increment,
169 //inc_DFS is a modification of DFS
170 static void inc_DFS(Graph& g,Graph& t,map& Increment,
171171 int events, Node *v, Edge e){
172
172
173173 vector allNodes=t.getAllNodes();
174174
175 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
175 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
176176 ++NI){
177177 Graph::nodeList node_list=t.getNodeList(*NI);
178 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
178 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
179179 NLI!= NLE; ++NLI){
180180 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
181181 if(!edgesEqual(f,e) && *v==*(f.getSecond())){
186186 }
187187 }
188188
189 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
189 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
190190 ++NI){
191191 Graph::nodeList node_list=t.getNodeList(*NI);
192 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
192 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
193193 NLI!=NLE; ++NLI){
194194 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
195195 if(!edgesEqual(f,e) && *v==*(f.getFirst())){
196196 int dir_count=inc_Dir(e,f);
197197 int wt=f.getWeight();
198 inc_DFS(g,t, Increment, dir_count*events+wt,
198 inc_DFS(g,t, Increment, dir_count*events+wt,
199199 f.getSecond(), f);
200200 }
201201 }
202202 }
203203
204204 allNodes=g.getAllNodes();
205 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
205 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
206206 ++NI){
207207 Graph::nodeList node_list=g.getNodeList(*NI);
208 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
208 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
209209 NLI!=NLE; ++NLI){
210210 Edge f(*NI, NLI->element,NLI->weight, NLI->randId);
211 if(!(t.hasEdgeAndWt(f)) && (*v==*(f.getSecond()) ||
211 if(!(t.hasEdgeAndWt(f)) && (*v==*(f.getSecond()) ||
212212 *v==*(f.getFirst()))){
213213 int dir_count=inc_Dir(e,f);
214214 Increment[f]+=dir_count*events;
218218 }
219219
220220 //Now we select a subset of all edges
221 //and assign them some values such that
221 //and assign them some values such that
222222 //if we consider just this subset, it still represents
223223 //the path sum along any path in the graph
224 static map getEdgeIncrements(Graph& g, Graph& t,
224 static map getEdgeIncrements(Graph& g, Graph& t,
225225 vector &be){
226226 //get all edges in g-t
227227 map Increment;
228228
229229 vector allNodes=g.getAllNodes();
230
231 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
230
231 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
232232 ++NI){
233233 Graph::nodeList node_list=g.getSortedNodeList(*NI, be);
234234 //modified g.getNodeList(*NI);
235 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
235 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
236236 NLI!=NLE; ++NLI){
237237 Edge ed(*NI, NLI->element,NLI->weight,NLI->randId);
238238 if(!(t.hasEdgeAndWt(ed))){
244244 Edge *ed=new Edge();
245245 inc_DFS(g,t,Increment, 0, g.getRoot(), *ed);
246246
247 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
247 for(vector::iterator NI=allNodes.begin(), NE=allNodes.end(); NI!=NE;
248248 ++NI){
249249 Graph::nodeList node_list=g.getSortedNodeList(*NI, be);
250250 //modified g.getNodeList(*NI);
251 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
251 for(Graph::nodeList::iterator NLI=node_list.begin(), NLE=node_list.end();
252252 NLI!=NLE; ++NLI){
253253 Edge ed(*NI, NLI->element,NLI->weight, NLI->randId);
254254 if(!(t.hasEdgeAndWt(ed))){
273273 //The idea here is to minimize the computation
274274 //by inserting only the needed code
275275 static void getCodeInsertions(Graph &g, map &instr,
276 vector &chords,
276 vector &chords,
277277 map &edIncrements){
278278
279279 //Register initialization code
284284 ws.pop_back();
285285 //for each edge v->w
286286 Graph::nodeList succs=g.getNodeList(v);
287
287
288288 for(Graph::nodeList::iterator nl=succs.begin(), ne=succs.end();
289289 nl!=ne; ++nl){
290290 int edgeWt=nl->weight;
319319
320320 /////Memory increment code
321321 ws.push_back(g.getExit());
322
322
323323 while(!ws.empty()) {
324324 Node *w=ws.back();
325325 ws.pop_back();
332332 Node *lnode=*EII;
333333 Graph::nodeList &nl = g.getNodeList(lnode);
334334 //graphListElement *N = findNodeInList(nl, w);
335 for(Graph::nodeList::const_iterator N = nl.begin(),
335 for(Graph::nodeList::const_iterator N = nl.begin(),
336336 NNEN = nl.end(); N!= NNEN; ++N){
337337 if (*N->element == *w){
338338 Node *v=lnode;
339
339
340340 //if chords has v->w
341341 Edge ed(v,w, N->weight, N->randId);
342342 getEdgeCode *edCd=new getEdgeCode();
358358 edCd->setInc(edIncrements[ed]);
359359 instr[ed]=edCd;
360360 }
361
361
362362 }
363363 else if(g.getNumberOfOutgoingEdges(v)==1)
364364 ws.push_back(v);
386386 //then incoming dummy edge is root->b
387387 //and outgoing dummy edge is a->exit
388388 //changed
389 void addDummyEdges(vector &stDummy,
390 vector &exDummy,
389 void addDummyEdges(vector &stDummy,
390 vector &exDummy,
391391 Graph &g, vector &be){
392392 for(vector::iterator VI=be.begin(), VE=be.end(); VI!=VE; ++VI){
393393 Edge ed=*VI;
419419
420420 //Move the incoming dummy edge code and outgoing dummy
421421 //edge code over to the corresponding back edge
422 static void moveDummyCode(vector &stDummy,
423 vector &exDummy,
424 vector &be,
425 map &insertions,
422 static void moveDummyCode(vector &stDummy,
423 vector &exDummy,
424 vector &be,
425 map &insertions,
426426 Graph &g){
427427 typedef vector::iterator vec_iter;
428
428
429429 map temp;
430430 //iterate over edges with code
431431 std::vector toErase;
432 for(map::iterator MI=insertions.begin(),
432 for(map::iterator MI=insertions.begin(),
433433 ME=insertions.end(); MI!=ME; ++MI){
434434 Edge ed=MI->first;
435435 getEdgeCode *edCd=MI->second;
461461 }
462462 }
463463 }
464
465 for(vector::iterator vmi=toErase.begin(), vme=toErase.end(); vmi!=vme;
464
465 for(vector::iterator vmi=toErase.begin(), vme=toErase.end(); vmi!=vme;
466466 ++vmi){
467467 insertions.erase(*vmi);
468468 g.removeEdgeWithWt(*vmi);
469469 }
470
471 for(map::iterator MI=temp.begin(),
470
471 for(map::iterator MI=temp.begin(),
472472 ME=temp.end(); MI!=ME; ++MI){
473473 insertions[MI->first]=MI->second;
474474 }
475
475
476476 #ifdef DEBUG_PATH_PROFILES
477477 cerr<<"size of deletions: "<
478478 cerr<<"SIZE OF INSERTIONS AFTER DEL "<
480480
481481 }
482482
483 //Do graph processing: to determine minimal edge increments,
483 //Do graph processing: to determine minimal edge increments,
484484 //appropriate code insertions etc and insert the code at
485485 //appropriate locations
486 void processGraph(Graph &g,
487 Instruction *rInst,
488 Value *countInst,
489 vector& be,
490 vector& stDummy,
491 vector& exDummy,
492 int numPaths, int MethNo,
486 void processGraph(Graph &g,
487 Instruction *rInst,
488 Value *countInst,
489 vector& be,
490 vector& stDummy,
491 vector& exDummy,
492 int numPaths, int MethNo,
493493 Value *threshold){
494494
495495 //Given a graph: with exit->root edge, do the following in seq:
504504 //5. Get edge increments
505505 //6. Get code insertions
506506 //7. move code on dummy edges over to the back edges
507
508
509 //This is used as maximum "weight" for
507
508
509 //This is used as maximum "weight" for
510510 //priority queue
511 //This would hold all
511 //This would hold all
512512 //right as long as number of paths in the graph
513513 //is less than this
514514 const int Infinity=99999999;
523523 //if its there earlier, remove it!
524524 //assign it weight Infinity
525525 //so that this edge IS ALWAYS IN spanning tree
526 //Note than edges in spanning tree do not get
526 //Note than edges in spanning tree do not get
527527 //instrumented: and we do not want the
528528 //edge exit->root to get instrumented
529529 //as it MAY BE a dummy edge
543543 #endif
544544 //now edges of tree t have weights reversed
545545 //(negative) because the algorithm used
546 //to find max spanning tree is
546 //to find max spanning tree is
547547 //actually for finding min spanning tree
548548 //so get back the original weights
549549 t->reverseWts();
550550
551551 //Ordinarily, the graph is directional
552 //lets converts the graph into an
552 //lets converts the graph into an
553553 //undirectional graph
554554 //This is done by adding an edge
555555 //v->u for all existing edges u->v
558558 //Given a tree t, and a "directed graph" g
559559 //replace the edges in the tree t with edges that exist in graph
560560 //The tree is formed from "undirectional" copy of graph
561 //So whatever edges the tree has, the undirectional graph
562 //would have too. This function corrects some of the directions in
561 //So whatever edges the tree has, the undirectional graph
562 //would have too. This function corrects some of the directions in
563563 //the tree so that now, all edge directions in the tree match
564564 //the edge directions of corresponding edges in the directed graph
565565 removeTreeEdges(g, *t);
587587 //step 5: Get edge increments
588588
589589 //Now we select a subset of all edges
590 //and assign them some values such that
590 //and assign them some values such that
591591 //if we consider just this subset, it still represents
592592 //the path sum along any path in the graph
593593
602602 std::cerr<<"-------end of edge increments\n";
603603 #endif
604604
605
605
606606 //step 6: Get code insertions
607
607
608608 //Based on edgeIncrements (above), now obtain
609609 //the kind of code to be inserted along an edge
610610 //The idea here is to minimize the computation
615615
616616 map codeInsertions;
617617 getCodeInsertions(g, codeInsertions, chords,increment);
618
618
619619 #ifdef DEBUG_PATH_PROFILES
620620 //print edges with code for debugging
621621 cerr<<"Code inserted in following---------------\n";
622 for(map::iterator cd_i=codeInsertions.begin(),
622 for(map::iterator cd_i=codeInsertions.begin(),
623623 cd_e=codeInsertions.end(); cd_i!=cd_e; ++cd_i){
624624 printEdge(cd_i->first);
625625 cerr<second->getCond()<<":"<second->getInc()<<"\n";
633633 //edge code over to the corresponding back edge
634634
635635 moveDummyCode(stDummy, exDummy, be, codeInsertions, g);
636
636
637637 #ifdef DEBUG_PATH_PROFILES
638638 //debugging info
639639 cerr<<"After moving dummy code\n";
640 for(map::iterator cd_i=codeInsertions.begin(),
640 for(map::iterator cd_i=codeInsertions.begin(),
641641 cd_e=codeInsertions.end(); cd_i != cd_e; ++cd_i){
642642 printEdge(cd_i->first);
643643 cerr<second->getCond()<<":"
649649
650650 //see what it looks like...
651651 //now insert code along edges which have codes on them
652 for(map::iterator MI=codeInsertions.begin(),
652 for(map::iterator MI=codeInsertions.begin(),
653653 ME=codeInsertions.end(); MI!=ME; ++MI){
654654 Edge ed=MI->first;
655655 insertBB(ed, MI->second, rInst, countInst, numPaths, MethNo, threshold);
656 }
656 }
657657 }
658658
659659 //print the graph (for debugging)
660660 void printGraph(Graph &g){
661661 vector lt=g.getAllNodes();
662662 cerr<<"Graph---------------------\n";
663 for(vector::iterator LI=lt.begin();
663 for(vector::iterator LI=lt.begin();
664664 LI!=lt.end(); ++LI){
665665 cerr<<((*LI)->getElement())->getName()<<"->";
666666 Graph::nodeList nl=g.getNodeList(*LI);
667 for(Graph::nodeList::iterator NI=nl.begin();
667 for(Graph::nodeList::iterator NI=nl.begin();
668668 NI!=nl.end(); ++NI){
669669 cerr<<":"<<"("<<(NI->element->getElement())
670670 ->getName()<<":"<element->getWeight()<<","<weight<<","
0 //===-- InstLoops.cpp -----------------------------------------------------===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This is the first-level instrumentation pass for the Reoptimizer. It
4545 DominatorSet *DS;
4646 void getBackEdgesVisit(BasicBlock *u,
4747 std::map &color,
48 std::map &d,
48 std::map &d,
4949 int &time, BBMap &be);
5050 void removeRedundant(BBMap &be);
5151 void findAndInstrumentBackEdges(Function &F);
5353 bool doInitialization(Module &M);
5454 bool runOnFunction(Function &F);
5555 };
56
56
5757 RegisterOpt X("instloops", "Instrument backedges for profiling");
5858 }
5959
60 //helper function to get back edges: it is called by
60 //helper function to get back edges: it is called by
6161 //the "getBackEdges" function below
6262 void InstLoops::getBackEdgesVisit(BasicBlock *u,
6363 std::map &color,
64 std::map &d,
64 std::map &d,
6565 int &time, BBMap &be) {
6666 color[u]=GREY;
6767 time++;
7373 if(color[BB]!=GREY && color[BB]!=BLACK){
7474 getBackEdgesVisit(BB, color, d, time, be);
7575 }
76
76
7777 //now checking for d and f vals
7878 else if(color[BB]==GREY){
7979 //so v is ancestor of u if time of u > time of v
9090 //set
9191 void InstLoops::removeRedundant(BBMap &be) {
9292 std::vector toDelete;
93 for(std::map::iterator MI = be.begin(),
93 for(std::map::iterator MI = be.begin(),
9494 ME = be.end(); MI != ME; ++MI)
9595 for(BBMap::iterator MMI = be.begin(), MME = be.end(); MMI != MME; ++MMI)
9696 if(DS->properlyDominates(MI->first, MMI->first))
9797 toDelete.push_back(MMI->first);
9898 // Remove all the back-edges we found from be.
99 for(std::vector::iterator VI = toDelete.begin(),
99 for(std::vector::iterator VI = toDelete.begin(),
100100 VE = toDelete.end(); VI != VE; ++VI)
101101 be.erase(*VI);
102102 }
136136
137137 assert(ti->getNumSuccessors() > index && "Not enough successors!");
138138 ti->setSuccessor(index, newBB);
139
139
140140 BasicBlock::InstListType < = newBB->getInstList();
141141 lt.push_back(new CallInst(inCountMth));
142142 new BranchInst(BB, newBB);
143
143
144144 // Now, set the sources of Phi nodes corresponding to the back-edge
145145 // in BB to come from the instrumentation block instead.
146 for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end();
146 for(BasicBlock::iterator BB2Inst = BB->begin(), BBend = BB->end();
147147 BB2Inst != BBend; ++BB2Inst) {
148148 if (PHINode *phiInst = dyn_cast(BB2Inst)) {
149149 int bbIndex = phiInst->getBasicBlockIndex(u);
0 //===-- ProfilePaths.cpp - interface to insert instrumentation --*- C++ -*-===//
1 //
1 //
22 // The LLVM Compiler Infrastructure
33 //
44 // This file was developed by the LLVM research group and is distributed under
55 // the University of Illinois Open Source License. See LICENSE.TXT for details.
6 //
6 //
77 //===----------------------------------------------------------------------===//
88 //
99 // This inserts instrumentation for counting execution of paths though a given
1010 // function Its implemented as a "Function" Pass, and called using opt
1111 //
12 // This pass is implemented by using algorithms similar to
13 // 1."Efficient Path Profiling": Ball, T. and Larus, J. R.,
12 // This pass is implemented by using algorithms similar to
13 // 1."Efficient Path Profiling": Ball, T. and Larus, J. R.,
1414 // Proceedings of Micro-29, Dec 1996, Paris, France.
1515 // 2."Efficiently Counting Program events with support for on-line
1616 // "queries": Ball T., ACM Transactions on Programming Languages
2121 // (implementation in Graph.cpp and GraphAuxiliary.cpp) and finally, appropriate
2222 // instrumentation is placed over suitable edges. (code inserted through
2323 // EdgeCode.cpp).
24 //
24 //
2525 // The algorithm inserts code such that every acyclic path in the CFG of a
2626 // function is identified through a unique number. the code insertion is optimal
2727 // in the sense that its inserted over a minimal set of edges. Also, the
4646 struct ProfilePaths : public FunctionPass {
4747 bool runOnFunction(Function &F);
4848
49 // Before this pass, make sure that there is only one
49 // Before this pass, make sure that there is only one
5050 // entry and only one exit node for the function in the CFG of the function
5151 //
5252 void getAnalysisUsage(AnalysisUsage &AU) const {
7575 if(F.isExternal()) {
7676 return false;
7777 }
78
78
7979 //increment counter for instrumented functions. mn is now function#
8080 mn++;
81
81
8282 // Transform the cfg s.t. we have just one exit node
83 BasicBlock *ExitNode =
84 getAnalysis().getReturnBlock();
83 BasicBlock *ExitNode =
84 getAnalysis().getReturnBlock();
8585
8686 //iterating over BBs and making graph
8787 std::vector nodes;
9191
9292 // The nodes must be uniquely identified:
9393 // That is, no two nodes must hav same BB*
94
94
9595 for (Function::iterator BB = F.begin(), BE = F.end(); BB != BE; ++BB) {
9696 Node *nd=new Node(BB);
97 nodes.push_back(nd);
97 nodes.push_back(nd);
9898 if(&*BB == ExitNode)
9999 exitNode=nd;
100100 if(BB==F.begin())
113113 edges.push_back(ed);
114114 }
115115 }
116
116
117117 Graph g(nodes,edges, startNode, exitNode);
118118
119 #ifdef DEBUG_PATH_PROFILES
119 #ifdef DEBUG_PATH_PROFILES
120120 std::cerr<<"Original graph\n";
121121 printGraph(g);
122122 #endif
123123
124124 BasicBlock *fr = &F.front();
125
125
126126 // The graph is made acyclic: this is done
127127 // by removing back edges for now, and adding them later on
128128