ExprTypeConvert.cpp 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. //===- ExprTypeConvert.cpp - Code to change an LLVM Expr Type -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by the LLVM research group and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the part of level raising that checks to see if it is
  11. // possible to coerce an entire expression tree into a different type. If
  12. // convertible, other routines from this file will do the conversion.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "TransformInternals.h"
  16. #include "llvm/Constants.h"
  17. #include "llvm/iOther.h"
  18. #include "llvm/iPHINode.h"
  19. #include "llvm/iMemory.h"
  20. #include "llvm/Analysis/Expressions.h"
  21. #include "Support/STLExtras.h"
  22. #include "Support/Debug.h"
  23. #include <algorithm>
  24. using namespace llvm;
  25. static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
  26. ValueTypeCache &ConvertedTypes,
  27. const TargetData &TD);
  28. static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
  29. ValueMapCache &VMC, const TargetData &TD);
  30. // Peephole Malloc instructions: we take a look at the use chain of the
  31. // malloc instruction, and try to find out if the following conditions hold:
  32. // 1. The malloc is of the form: 'malloc [sbyte], uint <constant>'
  33. // 2. The only users of the malloc are cast & add instructions
  34. // 3. Of the cast instructions, there is only one destination pointer type
  35. // [RTy] where the size of the pointed to object is equal to the number
  36. // of bytes allocated.
  37. //
  38. // If these conditions hold, we convert the malloc to allocate an [RTy]
  39. // element. TODO: This comment is out of date WRT arrays
  40. //
  41. static bool MallocConvertibleToType(MallocInst *MI, const Type *Ty,
  42. ValueTypeCache &CTMap,
  43. const TargetData &TD) {
  44. if (!isa<PointerType>(Ty)) return false; // Malloc always returns pointers
  45. // Deal with the type to allocate, not the pointer type...
  46. Ty = cast<PointerType>(Ty)->getElementType();
  47. if (!Ty->isSized()) return false; // Can only alloc something with a size
  48. // Analyze the number of bytes allocated...
  49. ExprType Expr = ClassifyExpr(MI->getArraySize());
  50. // Get information about the base datatype being allocated, before & after
  51. int ReqTypeSize = TD.getTypeSize(Ty);
  52. if (ReqTypeSize == 0) return false;
  53. unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
  54. // Must have a scale or offset to analyze it...
  55. if (!Expr.Offset && !Expr.Scale && OldTypeSize == 1) return false;
  56. // Get the offset and scale of the allocation...
  57. int64_t OffsetVal = Expr.Offset ? getConstantValue(Expr.Offset) : 0;
  58. int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) :(Expr.Var != 0);
  59. // The old type might not be of unit size, take old size into consideration
  60. // here...
  61. int64_t Offset = OffsetVal * OldTypeSize;
  62. int64_t Scale = ScaleVal * OldTypeSize;
  63. // In order to be successful, both the scale and the offset must be a multiple
  64. // of the requested data type's size.
  65. //
  66. if (Offset/ReqTypeSize*ReqTypeSize != Offset ||
  67. Scale/ReqTypeSize*ReqTypeSize != Scale)
  68. return false; // Nope.
  69. return true;
  70. }
  71. static Instruction *ConvertMallocToType(MallocInst *MI, const Type *Ty,
  72. const std::string &Name,
  73. ValueMapCache &VMC,
  74. const TargetData &TD){
  75. BasicBlock *BB = MI->getParent();
  76. BasicBlock::iterator It = BB->end();
  77. // Analyze the number of bytes allocated...
  78. ExprType Expr = ClassifyExpr(MI->getArraySize());
  79. const PointerType *AllocTy = cast<PointerType>(Ty);
  80. const Type *ElType = AllocTy->getElementType();
  81. unsigned DataSize = TD.getTypeSize(ElType);
  82. unsigned OldTypeSize = TD.getTypeSize(MI->getType()->getElementType());
  83. // Get the offset and scale coefficients that we are allocating...
  84. int64_t OffsetVal = (Expr.Offset ? getConstantValue(Expr.Offset) : 0);
  85. int64_t ScaleVal = Expr.Scale ? getConstantValue(Expr.Scale) : (Expr.Var !=0);
  86. // The old type might not be of unit size, take old size into consideration
  87. // here...
  88. unsigned Offset = (uint64_t)OffsetVal * OldTypeSize / DataSize;
  89. unsigned Scale = (uint64_t)ScaleVal * OldTypeSize / DataSize;
  90. // Locate the malloc instruction, because we may be inserting instructions
  91. It = MI;
  92. // If we have a scale, apply it first...
  93. if (Expr.Var) {
  94. // Expr.Var is not necessarily unsigned right now, insert a cast now.
  95. if (Expr.Var->getType() != Type::UIntTy)
  96. Expr.Var = new CastInst(Expr.Var, Type::UIntTy,
  97. Expr.Var->getName()+"-uint", It);
  98. if (Scale != 1)
  99. Expr.Var = BinaryOperator::create(Instruction::Mul, Expr.Var,
  100. ConstantUInt::get(Type::UIntTy, Scale),
  101. Expr.Var->getName()+"-scl", It);
  102. } else {
  103. // If we are not scaling anything, just make the offset be the "var"...
  104. Expr.Var = ConstantUInt::get(Type::UIntTy, Offset);
  105. Offset = 0; Scale = 1;
  106. }
  107. // If we have an offset now, add it in...
  108. if (Offset != 0) {
  109. assert(Expr.Var && "Var must be nonnull by now!");
  110. Expr.Var = BinaryOperator::create(Instruction::Add, Expr.Var,
  111. ConstantUInt::get(Type::UIntTy, Offset),
  112. Expr.Var->getName()+"-off", It);
  113. }
  114. assert(AllocTy == Ty);
  115. return new MallocInst(AllocTy->getElementType(), Expr.Var, Name);
  116. }
  117. // ExpressionConvertibleToType - Return true if it is possible
  118. bool llvm::ExpressionConvertibleToType(Value *V, const Type *Ty,
  119. ValueTypeCache &CTMap, const TargetData &TD) {
  120. // Expression type must be holdable in a register.
  121. if (!Ty->isFirstClassType())
  122. return false;
  123. ValueTypeCache::iterator CTMI = CTMap.find(V);
  124. if (CTMI != CTMap.end()) return CTMI->second == Ty;
  125. // If it's a constant... all constants can be converted to a different
  126. // type.
  127. //
  128. if (Constant *CPV = dyn_cast<Constant>(V))
  129. return true;
  130. CTMap[V] = Ty;
  131. if (V->getType() == Ty) return true; // Expression already correct type!
  132. Instruction *I = dyn_cast<Instruction>(V);
  133. if (I == 0) return false; // Otherwise, we can't convert!
  134. switch (I->getOpcode()) {
  135. case Instruction::Cast:
  136. // We can convert the expr if the cast destination type is losslessly
  137. // convertible to the requested type.
  138. if (!Ty->isLosslesslyConvertibleTo(I->getType())) return false;
  139. // We also do not allow conversion of a cast that casts from a ptr to array
  140. // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
  141. //
  142. if (const PointerType *SPT =
  143. dyn_cast<PointerType>(I->getOperand(0)->getType()))
  144. if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
  145. if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
  146. if (AT->getElementType() == DPT->getElementType())
  147. return false;
  148. break;
  149. case Instruction::Add:
  150. case Instruction::Sub:
  151. if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
  152. if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD) ||
  153. !ExpressionConvertibleToType(I->getOperand(1), Ty, CTMap, TD))
  154. return false;
  155. break;
  156. case Instruction::Shr:
  157. if (!Ty->isInteger()) return false;
  158. if (Ty->isSigned() != V->getType()->isSigned()) return false;
  159. // FALL THROUGH
  160. case Instruction::Shl:
  161. if (!Ty->isInteger()) return false;
  162. if (!ExpressionConvertibleToType(I->getOperand(0), Ty, CTMap, TD))
  163. return false;
  164. break;
  165. case Instruction::Load: {
  166. LoadInst *LI = cast<LoadInst>(I);
  167. if (!ExpressionConvertibleToType(LI->getPointerOperand(),
  168. PointerType::get(Ty), CTMap, TD))
  169. return false;
  170. break;
  171. }
  172. case Instruction::PHI: {
  173. PHINode *PN = cast<PHINode>(I);
  174. // Be conservative if we find a giant PHI node.
  175. if (PN->getNumIncomingValues() > 32) return false;
  176. for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
  177. if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
  178. return false;
  179. break;
  180. }
  181. case Instruction::Malloc:
  182. if (!MallocConvertibleToType(cast<MallocInst>(I), Ty, CTMap, TD))
  183. return false;
  184. break;
  185. case Instruction::GetElementPtr: {
  186. // GetElementPtr's are directly convertible to a pointer type if they have
  187. // a number of zeros at the end. Because removing these values does not
  188. // change the logical offset of the GEP, it is okay and fair to remove them.
  189. // This can change this:
  190. // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
  191. // %t2 = cast %List * * %t1 to %List *
  192. // into
  193. // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
  194. //
  195. GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
  196. const PointerType *PTy = dyn_cast<PointerType>(Ty);
  197. if (!PTy) return false; // GEP must always return a pointer...
  198. const Type *PVTy = PTy->getElementType();
  199. // Check to see if there are zero elements that we can remove from the
  200. // index array. If there are, check to see if removing them causes us to
  201. // get to the right type...
  202. //
  203. std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
  204. const Type *BaseType = GEP->getPointerOperand()->getType();
  205. const Type *ElTy = 0;
  206. while (!Indices.empty() &&
  207. Indices.back() == Constant::getNullValue(Indices.back()->getType())){
  208. Indices.pop_back();
  209. ElTy = GetElementPtrInst::getIndexedType(BaseType, Indices, true);
  210. if (ElTy == PVTy)
  211. break; // Found a match!!
  212. ElTy = 0;
  213. }
  214. if (ElTy) break; // Found a number of zeros we can strip off!
  215. // Otherwise, we can convert a GEP from one form to the other iff the
  216. // current gep is of the form 'getelementptr sbyte*, long N
  217. // and we could convert this to an appropriate GEP for the new type.
  218. //
  219. if (GEP->getNumOperands() == 2 &&
  220. GEP->getType() == PointerType::get(Type::SByteTy)) {
  221. // Do not Check to see if our incoming pointer can be converted
  222. // to be a ptr to an array of the right type... because in more cases than
  223. // not, it is simply not analyzable because of pointer/array
  224. // discrepancies. To fix this, we will insert a cast before the GEP.
  225. //
  226. // Check to see if 'N' is an expression that can be converted to
  227. // the appropriate size... if so, allow it.
  228. //
  229. std::vector<Value*> Indices;
  230. const Type *ElTy = ConvertibleToGEP(PTy, I->getOperand(1), Indices, TD);
  231. if (ElTy == PVTy) {
  232. if (!ExpressionConvertibleToType(I->getOperand(0),
  233. PointerType::get(ElTy), CTMap, TD))
  234. return false; // Can't continue, ExConToTy might have polluted set!
  235. break;
  236. }
  237. }
  238. // Otherwise, it could be that we have something like this:
  239. // getelementptr [[sbyte] *] * %reg115, long %reg138 ; [sbyte]**
  240. // and want to convert it into something like this:
  241. // getelemenptr [[int] *] * %reg115, long %reg138 ; [int]**
  242. //
  243. if (GEP->getNumOperands() == 2 &&
  244. PTy->getElementType()->isSized() &&
  245. TD.getTypeSize(PTy->getElementType()) ==
  246. TD.getTypeSize(GEP->getType()->getElementType())) {
  247. const PointerType *NewSrcTy = PointerType::get(PVTy);
  248. if (!ExpressionConvertibleToType(I->getOperand(0), NewSrcTy, CTMap, TD))
  249. return false;
  250. break;
  251. }
  252. return false; // No match, maybe next time.
  253. }
  254. case Instruction::Call: {
  255. if (isa<Function>(I->getOperand(0)))
  256. return false; // Don't even try to change direct calls.
  257. // If this is a function pointer, we can convert the return type if we can
  258. // convert the source function pointer.
  259. //
  260. const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
  261. const FunctionType *FT = cast<FunctionType>(PT->getElementType());
  262. std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
  263. const FunctionType *NewTy =
  264. FunctionType::get(Ty, ArgTys, FT->isVarArg());
  265. if (!ExpressionConvertibleToType(I->getOperand(0),
  266. PointerType::get(NewTy), CTMap, TD))
  267. return false;
  268. break;
  269. }
  270. default:
  271. return false;
  272. }
  273. // Expressions are only convertible if all of the users of the expression can
  274. // have this value converted. This makes use of the map to avoid infinite
  275. // recursion.
  276. //
  277. for (Value::use_iterator It = I->use_begin(), E = I->use_end(); It != E; ++It)
  278. if (!OperandConvertibleToType(*It, I, Ty, CTMap, TD))
  279. return false;
  280. return true;
  281. }
  282. Value *llvm::ConvertExpressionToType(Value *V, const Type *Ty,
  283. ValueMapCache &VMC, const TargetData &TD) {
  284. if (V->getType() == Ty) return V; // Already where we need to be?
  285. ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(V);
  286. if (VMCI != VMC.ExprMap.end()) {
  287. const Value *GV = VMCI->second;
  288. const Type *GTy = VMCI->second->getType();
  289. assert(VMCI->second->getType() == Ty);
  290. if (Instruction *I = dyn_cast<Instruction>(V))
  291. ValueHandle IHandle(VMC, I); // Remove I if it is unused now!
  292. return VMCI->second;
  293. }
  294. DEBUG(std::cerr << "CETT: " << (void*)V << " " << V);
  295. Instruction *I = dyn_cast<Instruction>(V);
  296. if (I == 0) {
  297. Constant *CPV = cast<Constant>(V);
  298. // Constants are converted by constant folding the cast that is required.
  299. // We assume here that all casts are implemented for constant prop.
  300. Value *Result = ConstantExpr::getCast(CPV, Ty);
  301. // Add the instruction to the expression map
  302. //VMC.ExprMap[V] = Result;
  303. return Result;
  304. }
  305. BasicBlock *BB = I->getParent();
  306. std::string Name = I->getName(); if (!Name.empty()) I->setName("");
  307. Instruction *Res; // Result of conversion
  308. ValueHandle IHandle(VMC, I); // Prevent I from being removed!
  309. Constant *Dummy = Constant::getNullValue(Ty);
  310. switch (I->getOpcode()) {
  311. case Instruction::Cast:
  312. assert(VMC.NewCasts.count(ValueHandle(VMC, I)) == 0);
  313. Res = new CastInst(I->getOperand(0), Ty, Name);
  314. VMC.NewCasts.insert(ValueHandle(VMC, Res));
  315. break;
  316. case Instruction::Add:
  317. case Instruction::Sub:
  318. Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
  319. Dummy, Dummy, Name);
  320. VMC.ExprMap[I] = Res; // Add node to expression eagerly
  321. Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
  322. Res->setOperand(1, ConvertExpressionToType(I->getOperand(1), Ty, VMC, TD));
  323. break;
  324. case Instruction::Shl:
  325. case Instruction::Shr:
  326. Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), Dummy,
  327. I->getOperand(1), Name);
  328. VMC.ExprMap[I] = Res;
  329. Res->setOperand(0, ConvertExpressionToType(I->getOperand(0), Ty, VMC, TD));
  330. break;
  331. case Instruction::Load: {
  332. LoadInst *LI = cast<LoadInst>(I);
  333. Res = new LoadInst(Constant::getNullValue(PointerType::get(Ty)), Name);
  334. VMC.ExprMap[I] = Res;
  335. Res->setOperand(0, ConvertExpressionToType(LI->getPointerOperand(),
  336. PointerType::get(Ty), VMC, TD));
  337. assert(Res->getOperand(0)->getType() == PointerType::get(Ty));
  338. assert(Ty == Res->getType());
  339. assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
  340. break;
  341. }
  342. case Instruction::PHI: {
  343. PHINode *OldPN = cast<PHINode>(I);
  344. PHINode *NewPN = new PHINode(Ty, Name);
  345. VMC.ExprMap[I] = NewPN; // Add node to expression eagerly
  346. while (OldPN->getNumOperands()) {
  347. BasicBlock *BB = OldPN->getIncomingBlock(0);
  348. Value *OldVal = OldPN->getIncomingValue(0);
  349. ValueHandle OldValHandle(VMC, OldVal);
  350. OldPN->removeIncomingValue(BB, false);
  351. Value *V = ConvertExpressionToType(OldVal, Ty, VMC, TD);
  352. NewPN->addIncoming(V, BB);
  353. }
  354. Res = NewPN;
  355. break;
  356. }
  357. case Instruction::Malloc: {
  358. Res = ConvertMallocToType(cast<MallocInst>(I), Ty, Name, VMC, TD);
  359. break;
  360. }
  361. case Instruction::GetElementPtr: {
  362. // GetElementPtr's are directly convertible to a pointer type if they have
  363. // a number of zeros at the end. Because removing these values does not
  364. // change the logical offset of the GEP, it is okay and fair to remove them.
  365. // This can change this:
  366. // %t1 = getelementptr %Hosp * %hosp, ubyte 4, ubyte 0 ; <%List **>
  367. // %t2 = cast %List * * %t1 to %List *
  368. // into
  369. // %t2 = getelementptr %Hosp * %hosp, ubyte 4 ; <%List *>
  370. //
  371. GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
  372. // Check to see if there are zero elements that we can remove from the
  373. // index array. If there are, check to see if removing them causes us to
  374. // get to the right type...
  375. //
  376. std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
  377. const Type *BaseType = GEP->getPointerOperand()->getType();
  378. const Type *PVTy = cast<PointerType>(Ty)->getElementType();
  379. Res = 0;
  380. while (!Indices.empty() &&
  381. Indices.back() == Constant::getNullValue(Indices.back()->getType())){
  382. Indices.pop_back();
  383. if (GetElementPtrInst::getIndexedType(BaseType, Indices, true) == PVTy) {
  384. if (Indices.size() == 0)
  385. Res = new CastInst(GEP->getPointerOperand(), BaseType); // NOOP CAST
  386. else
  387. Res = new GetElementPtrInst(GEP->getPointerOperand(), Indices, Name);
  388. break;
  389. }
  390. }
  391. if (Res == 0 && GEP->getNumOperands() == 2 &&
  392. GEP->getType() == PointerType::get(Type::SByteTy)) {
  393. // Otherwise, we can convert a GEP from one form to the other iff the
  394. // current gep is of the form 'getelementptr sbyte*, unsigned N
  395. // and we could convert this to an appropriate GEP for the new type.
  396. //
  397. const PointerType *NewSrcTy = PointerType::get(PVTy);
  398. BasicBlock::iterator It = I;
  399. // Check to see if 'N' is an expression that can be converted to
  400. // the appropriate size... if so, allow it.
  401. //
  402. std::vector<Value*> Indices;
  403. const Type *ElTy = ConvertibleToGEP(NewSrcTy, I->getOperand(1),
  404. Indices, TD, &It);
  405. if (ElTy) {
  406. assert(ElTy == PVTy && "Internal error, setup wrong!");
  407. Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
  408. Indices, Name);
  409. VMC.ExprMap[I] = Res;
  410. Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
  411. NewSrcTy, VMC, TD));
  412. }
  413. }
  414. // Otherwise, it could be that we have something like this:
  415. // getelementptr [[sbyte] *] * %reg115, uint %reg138 ; [sbyte]**
  416. // and want to convert it into something like this:
  417. // getelemenptr [[int] *] * %reg115, uint %reg138 ; [int]**
  418. //
  419. if (Res == 0) {
  420. const PointerType *NewSrcTy = PointerType::get(PVTy);
  421. std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
  422. Res = new GetElementPtrInst(Constant::getNullValue(NewSrcTy),
  423. Indices, Name);
  424. VMC.ExprMap[I] = Res;
  425. Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
  426. NewSrcTy, VMC, TD));
  427. }
  428. assert(Res && "Didn't find match!");
  429. break;
  430. }
  431. case Instruction::Call: {
  432. assert(!isa<Function>(I->getOperand(0)));
  433. // If this is a function pointer, we can convert the return type if we can
  434. // convert the source function pointer.
  435. //
  436. const PointerType *PT = cast<PointerType>(I->getOperand(0)->getType());
  437. const FunctionType *FT = cast<FunctionType>(PT->getElementType());
  438. std::vector<const Type *> ArgTys(FT->param_begin(), FT->param_end());
  439. const FunctionType *NewTy =
  440. FunctionType::get(Ty, ArgTys, FT->isVarArg());
  441. const PointerType *NewPTy = PointerType::get(NewTy);
  442. if (Ty == Type::VoidTy)
  443. Name = ""; // Make sure not to name calls that now return void!
  444. Res = new CallInst(Constant::getNullValue(NewPTy),
  445. std::vector<Value*>(I->op_begin()+1, I->op_end()),
  446. Name);
  447. VMC.ExprMap[I] = Res;
  448. Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),NewPTy,VMC,TD));
  449. break;
  450. }
  451. default:
  452. assert(0 && "Expression convertible, but don't know how to convert?");
  453. return 0;
  454. }
  455. assert(Res->getType() == Ty && "Didn't convert expr to correct type!");
  456. BB->getInstList().insert(I, Res);
  457. // Add the instruction to the expression map
  458. VMC.ExprMap[I] = Res;
  459. unsigned NumUses = I->use_size();
  460. for (unsigned It = 0; It < NumUses; ) {
  461. unsigned OldSize = NumUses;
  462. Value::use_iterator UI = I->use_begin();
  463. std::advance(UI, It);
  464. ConvertOperandToType(*UI, I, Res, VMC, TD);
  465. NumUses = I->use_size();
  466. if (NumUses == OldSize) ++It;
  467. }
  468. DEBUG(std::cerr << "ExpIn: " << (void*)I << " " << I
  469. << "ExpOut: " << (void*)Res << " " << Res);
  470. return Res;
  471. }
  472. // ValueConvertibleToType - Return true if it is possible
  473. bool llvm::ValueConvertibleToType(Value *V, const Type *Ty,
  474. ValueTypeCache &ConvertedTypes,
  475. const TargetData &TD) {
  476. ValueTypeCache::iterator I = ConvertedTypes.find(V);
  477. if (I != ConvertedTypes.end()) return I->second == Ty;
  478. ConvertedTypes[V] = Ty;
  479. // It is safe to convert the specified value to the specified type IFF all of
  480. // the uses of the value can be converted to accept the new typed value.
  481. //
  482. if (V->getType() != Ty) {
  483. for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I)
  484. if (!OperandConvertibleToType(*I, V, Ty, ConvertedTypes, TD))
  485. return false;
  486. }
  487. return true;
  488. }
  489. // OperandConvertibleToType - Return true if it is possible to convert operand
  490. // V of User (instruction) U to the specified type. This is true iff it is
  491. // possible to change the specified instruction to accept this. CTMap is a map
  492. // of converted types, so that circular definitions will see the future type of
  493. // the expression, not the static current type.
  494. //
  495. static bool OperandConvertibleToType(User *U, Value *V, const Type *Ty,
  496. ValueTypeCache &CTMap,
  497. const TargetData &TD) {
  498. // if (V->getType() == Ty) return true; // Operand already the right type?
  499. // Expression type must be holdable in a register.
  500. if (!Ty->isFirstClassType())
  501. return false;
  502. Instruction *I = dyn_cast<Instruction>(U);
  503. if (I == 0) return false; // We can't convert!
  504. switch (I->getOpcode()) {
  505. case Instruction::Cast:
  506. assert(I->getOperand(0) == V);
  507. // We can convert the expr if the cast destination type is losslessly
  508. // convertible to the requested type.
  509. // Also, do not change a cast that is a noop cast. For all intents and
  510. // purposes it should be eliminated.
  511. if (!Ty->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) ||
  512. I->getType() == I->getOperand(0)->getType())
  513. return false;
  514. // Do not allow a 'cast ushort %V to uint' to have it's first operand be
  515. // converted to a 'short' type. Doing so changes the way sign promotion
  516. // happens, and breaks things. Only allow the cast to take place if the
  517. // signedness doesn't change... or if the current cast is not a lossy
  518. // conversion.
  519. //
  520. if (!I->getType()->isLosslesslyConvertibleTo(I->getOperand(0)->getType()) &&
  521. I->getOperand(0)->getType()->isSigned() != Ty->isSigned())
  522. return false;
  523. // We also do not allow conversion of a cast that casts from a ptr to array
  524. // of X to a *X. For example: cast [4 x %List *] * %val to %List * *
  525. //
  526. if (const PointerType *SPT =
  527. dyn_cast<PointerType>(I->getOperand(0)->getType()))
  528. if (const PointerType *DPT = dyn_cast<PointerType>(I->getType()))
  529. if (const ArrayType *AT = dyn_cast<ArrayType>(SPT->getElementType()))
  530. if (AT->getElementType() == DPT->getElementType())
  531. return false;
  532. return true;
  533. case Instruction::Add:
  534. if (isa<PointerType>(Ty)) {
  535. Value *IndexVal = I->getOperand(V == I->getOperand(0) ? 1 : 0);
  536. std::vector<Value*> Indices;
  537. if (const Type *ETy = ConvertibleToGEP(Ty, IndexVal, Indices, TD)) {
  538. const Type *RetTy = PointerType::get(ETy);
  539. // Only successful if we can convert this type to the required type
  540. if (ValueConvertibleToType(I, RetTy, CTMap, TD)) {
  541. CTMap[I] = RetTy;
  542. return true;
  543. }
  544. // We have to return failure here because ValueConvertibleToType could
  545. // have polluted our map
  546. return false;
  547. }
  548. }
  549. // FALLTHROUGH
  550. case Instruction::Sub: {
  551. if (!Ty->isInteger() && !Ty->isFloatingPoint()) return false;
  552. Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
  553. return ValueConvertibleToType(I, Ty, CTMap, TD) &&
  554. ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
  555. }
  556. case Instruction::SetEQ:
  557. case Instruction::SetNE: {
  558. Value *OtherOp = I->getOperand((V == I->getOperand(0)) ? 1 : 0);
  559. return ExpressionConvertibleToType(OtherOp, Ty, CTMap, TD);
  560. }
  561. case Instruction::Shr:
  562. if (Ty->isSigned() != V->getType()->isSigned()) return false;
  563. // FALL THROUGH
  564. case Instruction::Shl:
  565. if (I->getOperand(1) == V) return false; // Cannot change shift amount type
  566. if (!Ty->isInteger()) return false;
  567. return ValueConvertibleToType(I, Ty, CTMap, TD);
  568. case Instruction::Free:
  569. assert(I->getOperand(0) == V);
  570. return isa<PointerType>(Ty); // Free can free any pointer type!
  571. case Instruction::Load:
  572. // Cannot convert the types of any subscripts...
  573. if (I->getOperand(0) != V) return false;
  574. if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
  575. LoadInst *LI = cast<LoadInst>(I);
  576. const Type *LoadedTy = PT->getElementType();
  577. // They could be loading the first element of a composite type...
  578. if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
  579. unsigned Offset = 0; // No offset, get first leaf.
  580. std::vector<Value*> Indices; // Discarded...
  581. LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
  582. assert(Offset == 0 && "Offset changed from zero???");
  583. }
  584. if (!LoadedTy->isFirstClassType())
  585. return false;
  586. if (TD.getTypeSize(LoadedTy) != TD.getTypeSize(LI->getType()))
  587. return false;
  588. return ValueConvertibleToType(LI, LoadedTy, CTMap, TD);
  589. }
  590. return false;
  591. case Instruction::Store: {
  592. StoreInst *SI = cast<StoreInst>(I);
  593. if (V == I->getOperand(0)) {
  594. ValueTypeCache::iterator CTMI = CTMap.find(I->getOperand(1));
  595. if (CTMI != CTMap.end()) { // Operand #1 is in the table already?
  596. // If so, check to see if it's Ty*, or, more importantly, if it is a
  597. // pointer to a structure where the first element is a Ty... this code
  598. // is necessary because we might be trying to change the source and
  599. // destination type of the store (they might be related) and the dest
  600. // pointer type might be a pointer to structure. Below we allow pointer
  601. // to structures where the 0th element is compatible with the value,
  602. // now we have to support the symmetrical part of this.
  603. //
  604. const Type *ElTy = cast<PointerType>(CTMI->second)->getElementType();
  605. // Already a pointer to what we want? Trivially accept...
  606. if (ElTy == Ty) return true;
  607. // Tricky case now, if the destination is a pointer to structure,
  608. // obviously the source is not allowed to be a structure (cannot copy
  609. // a whole structure at a time), so the level raiser must be trying to
  610. // store into the first field. Check for this and allow it now:
  611. //
  612. if (const StructType *SElTy = dyn_cast<StructType>(ElTy)) {
  613. unsigned Offset = 0;
  614. std::vector<Value*> Indices;
  615. ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
  616. assert(Offset == 0 && "Offset changed!");
  617. if (ElTy == 0) // Element at offset zero in struct doesn't exist!
  618. return false; // Can only happen for {}*
  619. if (ElTy == Ty) // Looks like the 0th element of structure is
  620. return true; // compatible! Accept now!
  621. // Otherwise we know that we can't work, so just stop trying now.
  622. return false;
  623. }
  624. }
  625. // Can convert the store if we can convert the pointer operand to match
  626. // the new value type...
  627. return ExpressionConvertibleToType(I->getOperand(1), PointerType::get(Ty),
  628. CTMap, TD);
  629. } else if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
  630. const Type *ElTy = PT->getElementType();
  631. assert(V == I->getOperand(1));
  632. if (isa<StructType>(ElTy)) {
  633. // We can change the destination pointer if we can store our first
  634. // argument into the first element of the structure...
  635. //
  636. unsigned Offset = 0;
  637. std::vector<Value*> Indices;
  638. ElTy = getStructOffsetType(ElTy, Offset, Indices, TD, false);
  639. assert(Offset == 0 && "Offset changed!");
  640. if (ElTy == 0) // Element at offset zero in struct doesn't exist!
  641. return false; // Can only happen for {}*
  642. }
  643. // Must move the same amount of data...
  644. if (!ElTy->isSized() ||
  645. TD.getTypeSize(ElTy) != TD.getTypeSize(I->getOperand(0)->getType()))
  646. return false;
  647. // Can convert store if the incoming value is convertible and if the
  648. // result will preserve semantics...
  649. const Type *Op0Ty = I->getOperand(0)->getType();
  650. if (!(Op0Ty->isIntegral() ^ ElTy->isIntegral()) &&
  651. !(Op0Ty->isFloatingPoint() ^ ElTy->isFloatingPoint()))
  652. return ExpressionConvertibleToType(I->getOperand(0), ElTy, CTMap, TD);
  653. }
  654. return false;
  655. }
  656. case Instruction::GetElementPtr:
  657. if (V != I->getOperand(0) || !isa<PointerType>(Ty)) return false;
  658. // If we have a two operand form of getelementptr, this is really little
  659. // more than a simple addition. As with addition, check to see if the
  660. // getelementptr instruction can be changed to index into the new type.
  661. //
  662. if (I->getNumOperands() == 2) {
  663. const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
  664. unsigned DataSize = TD.getTypeSize(OldElTy);
  665. Value *Index = I->getOperand(1);
  666. Instruction *TempScale = 0;
  667. // If the old data element is not unit sized, we have to create a scale
  668. // instruction so that ConvertibleToGEP will know the REAL amount we are
  669. // indexing by. Note that this is never inserted into the instruction
  670. // stream, so we have to delete it when we're done.
  671. //
  672. if (DataSize != 1) {
  673. Value *CST;
  674. if (Index->getType()->isSigned())
  675. CST = ConstantSInt::get(Index->getType(), DataSize);
  676. else
  677. CST = ConstantUInt::get(Index->getType(), DataSize);
  678. TempScale = BinaryOperator::create(Instruction::Mul, Index, CST);
  679. Index = TempScale;
  680. }
  681. // Check to see if the second argument is an expression that can
  682. // be converted to the appropriate size... if so, allow it.
  683. //
  684. std::vector<Value*> Indices;
  685. const Type *ElTy = ConvertibleToGEP(Ty, Index, Indices, TD);
  686. delete TempScale; // Free our temporary multiply if we made it
  687. if (ElTy == 0) return false; // Cannot make conversion...
  688. return ValueConvertibleToType(I, PointerType::get(ElTy), CTMap, TD);
  689. }
  690. return false;
  691. case Instruction::PHI: {
  692. PHINode *PN = cast<PHINode>(I);
  693. // Be conservative if we find a giant PHI node.
  694. if (PN->getNumIncomingValues() > 32) return false;
  695. for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i)
  696. if (!ExpressionConvertibleToType(PN->getIncomingValue(i), Ty, CTMap, TD))
  697. return false;
  698. return ValueConvertibleToType(PN, Ty, CTMap, TD);
  699. }
  700. case Instruction::Call: {
  701. User::op_iterator OI = find(I->op_begin(), I->op_end(), V);
  702. assert (OI != I->op_end() && "Not using value!");
  703. unsigned OpNum = OI - I->op_begin();
  704. // Are we trying to change the function pointer value to a new type?
  705. if (OpNum == 0) {
  706. const PointerType *PTy = dyn_cast<PointerType>(Ty);
  707. if (PTy == 0) return false; // Can't convert to a non-pointer type...
  708. const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
  709. if (FTy == 0) return false; // Can't convert to a non ptr to function...
  710. // Do not allow converting to a call where all of the operands are ...'s
  711. if (FTy->getNumParams() == 0 && FTy->isVarArg())
  712. return false; // Do not permit this conversion!
  713. // Perform sanity checks to make sure that new function type has the
  714. // correct number of arguments...
  715. //
  716. unsigned NumArgs = I->getNumOperands()-1; // Don't include function ptr
  717. // Cannot convert to a type that requires more fixed arguments than
  718. // the call provides...
  719. //
  720. if (NumArgs < FTy->getNumParams()) return false;
  721. // Unless this is a vararg function type, we cannot provide more arguments
  722. // than are desired...
  723. //
  724. if (!FTy->isVarArg() && NumArgs > FTy->getNumParams())
  725. return false;
  726. // Okay, at this point, we know that the call and the function type match
  727. // number of arguments. Now we see if we can convert the arguments
  728. // themselves. Note that we do not require operands to be convertible,
  729. // we can insert casts if they are convertible but not compatible. The
  730. // reason for this is that we prefer to have resolved functions but casted
  731. // arguments if possible.
  732. //
  733. for (unsigned i = 0, NA = FTy->getNumParams(); i < NA; ++i)
  734. if (!FTy->getParamType(i)->isLosslesslyConvertibleTo(I->getOperand(i+1)->getType()))
  735. return false; // Operands must have compatible types!
  736. // Okay, at this point, we know that all of the arguments can be
  737. // converted. We succeed if we can change the return type if
  738. // necessary...
  739. //
  740. return ValueConvertibleToType(I, FTy->getReturnType(), CTMap, TD);
  741. }
  742. const PointerType *MPtr = cast<PointerType>(I->getOperand(0)->getType());
  743. const FunctionType *FTy = cast<FunctionType>(MPtr->getElementType());
  744. if (!FTy->isVarArg()) return false;
  745. if ((OpNum-1) < FTy->getNumParams())
  746. return false; // It's not in the varargs section...
  747. // If we get this far, we know the value is in the varargs section of the
  748. // function! We can convert if we don't reinterpret the value...
  749. //
  750. return Ty->isLosslesslyConvertibleTo(V->getType());
  751. }
  752. }
  753. return false;
  754. }
  755. void llvm::ConvertValueToNewType(Value *V, Value *NewVal, ValueMapCache &VMC,
  756. const TargetData &TD) {
  757. ValueHandle VH(VMC, V);
  758. unsigned NumUses = V->use_size();
  759. for (unsigned It = 0; It < NumUses; ) {
  760. unsigned OldSize = NumUses;
  761. Value::use_iterator UI = V->use_begin();
  762. std::advance(UI, It);
  763. ConvertOperandToType(*UI, V, NewVal, VMC, TD);
  764. NumUses = V->use_size();
  765. if (NumUses == OldSize) ++It;
  766. }
  767. }
  768. static void ConvertOperandToType(User *U, Value *OldVal, Value *NewVal,
  769. ValueMapCache &VMC, const TargetData &TD) {
  770. if (isa<ValueHandle>(U)) return; // Valuehandles don't let go of operands...
  771. if (VMC.OperandsMapped.count(U)) return;
  772. VMC.OperandsMapped.insert(U);
  773. ValueMapCache::ExprMapTy::iterator VMCI = VMC.ExprMap.find(U);
  774. if (VMCI != VMC.ExprMap.end())
  775. return;
  776. Instruction *I = cast<Instruction>(U); // Only Instructions convertible
  777. BasicBlock *BB = I->getParent();
  778. assert(BB != 0 && "Instruction not embedded in basic block!");
  779. std::string Name = I->getName();
  780. I->setName("");
  781. Instruction *Res; // Result of conversion
  782. //std::cerr << endl << endl << "Type:\t" << Ty << "\nInst: " << I
  783. // << "BB Before: " << BB << endl;
  784. // Prevent I from being removed...
  785. ValueHandle IHandle(VMC, I);
  786. const Type *NewTy = NewVal->getType();
  787. Constant *Dummy = (NewTy != Type::VoidTy) ?
  788. Constant::getNullValue(NewTy) : 0;
  789. switch (I->getOpcode()) {
  790. case Instruction::Cast:
  791. if (VMC.NewCasts.count(ValueHandle(VMC, I))) {
  792. // This cast has already had it's value converted, causing a new cast to
  793. // be created. We don't want to create YET ANOTHER cast instruction
  794. // representing the original one, so just modify the operand of this cast
  795. // instruction, which we know is newly created.
  796. I->setOperand(0, NewVal);
  797. I->setName(Name); // give I its name back
  798. return;
  799. } else {
  800. Res = new CastInst(NewVal, I->getType(), Name);
  801. }
  802. break;
  803. case Instruction::Add:
  804. if (isa<PointerType>(NewTy)) {
  805. Value *IndexVal = I->getOperand(OldVal == I->getOperand(0) ? 1 : 0);
  806. std::vector<Value*> Indices;
  807. BasicBlock::iterator It = I;
  808. if (const Type *ETy = ConvertibleToGEP(NewTy, IndexVal, Indices, TD,&It)){
  809. // If successful, convert the add to a GEP
  810. //const Type *RetTy = PointerType::get(ETy);
  811. // First operand is actually the given pointer...
  812. Res = new GetElementPtrInst(NewVal, Indices, Name);
  813. assert(cast<PointerType>(Res->getType())->getElementType() == ETy &&
  814. "ConvertibleToGEP broken!");
  815. break;
  816. }
  817. }
  818. // FALLTHROUGH
  819. case Instruction::Sub:
  820. case Instruction::SetEQ:
  821. case Instruction::SetNE: {
  822. Res = BinaryOperator::create(cast<BinaryOperator>(I)->getOpcode(),
  823. Dummy, Dummy, Name);
  824. VMC.ExprMap[I] = Res; // Add node to expression eagerly
  825. unsigned OtherIdx = (OldVal == I->getOperand(0)) ? 1 : 0;
  826. Value *OtherOp = I->getOperand(OtherIdx);
  827. Value *NewOther = ConvertExpressionToType(OtherOp, NewTy, VMC, TD);
  828. Res->setOperand(OtherIdx, NewOther);
  829. Res->setOperand(!OtherIdx, NewVal);
  830. break;
  831. }
  832. case Instruction::Shl:
  833. case Instruction::Shr:
  834. assert(I->getOperand(0) == OldVal);
  835. Res = new ShiftInst(cast<ShiftInst>(I)->getOpcode(), NewVal,
  836. I->getOperand(1), Name);
  837. break;
  838. case Instruction::Free: // Free can free any pointer type!
  839. assert(I->getOperand(0) == OldVal);
  840. Res = new FreeInst(NewVal);
  841. break;
  842. case Instruction::Load: {
  843. assert(I->getOperand(0) == OldVal && isa<PointerType>(NewVal->getType()));
  844. const Type *LoadedTy =
  845. cast<PointerType>(NewVal->getType())->getElementType();
  846. Value *Src = NewVal;
  847. if (const CompositeType *CT = dyn_cast<CompositeType>(LoadedTy)) {
  848. std::vector<Value*> Indices;
  849. Indices.push_back(Constant::getNullValue(Type::UIntTy));
  850. unsigned Offset = 0; // No offset, get first leaf.
  851. LoadedTy = getStructOffsetType(CT, Offset, Indices, TD, false);
  852. assert(LoadedTy->isFirstClassType());
  853. if (Indices.size() != 1) { // Do not generate load X, 0
  854. // Insert the GEP instruction before this load.
  855. Src = new GetElementPtrInst(Src, Indices, Name+".idx", I);
  856. }
  857. }
  858. Res = new LoadInst(Src, Name);
  859. assert(Res->getType()->isFirstClassType() && "Load of structure or array!");
  860. break;
  861. }
  862. case Instruction::Store: {
  863. if (I->getOperand(0) == OldVal) { // Replace the source value
  864. // Check to see if operand #1 has already been converted...
  865. ValueMapCache::ExprMapTy::iterator VMCI =
  866. VMC.ExprMap.find(I->getOperand(1));
  867. if (VMCI != VMC.ExprMap.end()) {
  868. // Comments describing this stuff are in the OperandConvertibleToType
  869. // switch statement for Store...
  870. //
  871. const Type *ElTy =
  872. cast<PointerType>(VMCI->second->getType())->getElementType();
  873. Value *SrcPtr = VMCI->second;
  874. if (ElTy != NewTy) {
  875. // We check that this is a struct in the initial scan...
  876. const StructType *SElTy = cast<StructType>(ElTy);
  877. std::vector<Value*> Indices;
  878. Indices.push_back(Constant::getNullValue(Type::UIntTy));
  879. unsigned Offset = 0;
  880. const Type *Ty = getStructOffsetType(ElTy, Offset, Indices, TD,false);
  881. assert(Offset == 0 && "Offset changed!");
  882. assert(NewTy == Ty && "Did not convert to correct type!");
  883. // Insert the GEP instruction before this store.
  884. SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
  885. SrcPtr->getName()+".idx", I);
  886. }
  887. Res = new StoreInst(NewVal, SrcPtr);
  888. VMC.ExprMap[I] = Res;
  889. } else {
  890. // Otherwise, we haven't converted Operand #1 over yet...
  891. const PointerType *NewPT = PointerType::get(NewTy);
  892. Res = new StoreInst(NewVal, Constant::getNullValue(NewPT));
  893. VMC.ExprMap[I] = Res;
  894. Res->setOperand(1, ConvertExpressionToType(I->getOperand(1),
  895. NewPT, VMC, TD));
  896. }
  897. } else { // Replace the source pointer
  898. const Type *ValTy = cast<PointerType>(NewTy)->getElementType();
  899. Value *SrcPtr = NewVal;
  900. if (isa<StructType>(ValTy)) {
  901. std::vector<Value*> Indices;
  902. Indices.push_back(Constant::getNullValue(Type::UIntTy));
  903. unsigned Offset = 0;
  904. ValTy = getStructOffsetType(ValTy, Offset, Indices, TD, false);
  905. assert(Offset == 0 && ValTy);
  906. // Insert the GEP instruction before this store.
  907. SrcPtr = new GetElementPtrInst(SrcPtr, Indices,
  908. SrcPtr->getName()+".idx", I);
  909. }
  910. Res = new StoreInst(Constant::getNullValue(ValTy), SrcPtr);
  911. VMC.ExprMap[I] = Res;
  912. Res->setOperand(0, ConvertExpressionToType(I->getOperand(0),
  913. ValTy, VMC, TD));
  914. }
  915. break;
  916. }
  917. case Instruction::GetElementPtr: {
  918. // Convert a one index getelementptr into just about anything that is
  919. // desired.
  920. //
  921. BasicBlock::iterator It = I;
  922. const Type *OldElTy = cast<PointerType>(I->getType())->getElementType();
  923. unsigned DataSize = TD.getTypeSize(OldElTy);
  924. Value *Index = I->getOperand(1);
  925. if (DataSize != 1) {
  926. // Insert a multiply of the old element type is not a unit size...
  927. Value *CST;
  928. if (Index->getType()->isSigned())
  929. CST = ConstantSInt::get(Index->getType(), DataSize);
  930. else
  931. CST = ConstantUInt::get(Index->getType(), DataSize);
  932. Index = BinaryOperator::create(Instruction::Mul, Index, CST, "scale", It);
  933. }
  934. // Perform the conversion now...
  935. //
  936. std::vector<Value*> Indices;
  937. const Type *ElTy = ConvertibleToGEP(NewVal->getType(),Index,Indices,TD,&It);
  938. assert(ElTy != 0 && "GEP Conversion Failure!");
  939. Res = new GetElementPtrInst(NewVal, Indices, Name);
  940. assert(Res->getType() == PointerType::get(ElTy) &&
  941. "ConvertibleToGet failed!");
  942. }
  943. #if 0
  944. if (I->getType() == PointerType::get(Type::SByteTy)) {
  945. // Convert a getelementptr sbyte * %reg111, uint 16 freely back to
  946. // anything that is a pointer type...
  947. //
  948. BasicBlock::iterator It = I;
  949. // Check to see if the second argument is an expression that can
  950. // be converted to the appropriate size... if so, allow it.
  951. //
  952. std::vector<Value*> Indices;
  953. const Type *ElTy = ConvertibleToGEP(NewVal->getType(), I->getOperand(1),
  954. Indices, TD, &It);
  955. assert(ElTy != 0 && "GEP Conversion Failure!");
  956. Res = new GetElementPtrInst(NewVal, Indices, Name);
  957. } else {
  958. // Convert a getelementptr ulong * %reg123, uint %N
  959. // to getelementptr long * %reg123, uint %N
  960. // ... where the type must simply stay the same size...
  961. //
  962. GetElementPtrInst *GEP = cast<GetElementPtrInst>(I);
  963. std::vector<Value*> Indices(GEP->idx_begin(), GEP->idx_end());
  964. Res = new GetElementPtrInst(NewVal, Indices, Name);
  965. }
  966. #endif
  967. break;
  968. case Instruction::PHI: {
  969. PHINode *OldPN = cast<PHINode>(I);
  970. PHINode *NewPN = new PHINode(NewTy, Name);
  971. VMC.ExprMap[I] = NewPN;
  972. while (OldPN->getNumOperands()) {
  973. BasicBlock *BB = OldPN->getIncomingBlock(0);
  974. Value *OldVal = OldPN->getIncomingValue(0);
  975. OldPN->removeIncomingValue(BB, false);
  976. Value *V = ConvertExpressionToType(OldVal, NewTy, VMC, TD);
  977. NewPN->addIncoming(V, BB);
  978. }
  979. Res = NewPN;
  980. break;
  981. }
  982. case Instruction::Call: {
  983. Value *Meth = I->getOperand(0);
  984. std::vector<Value*> Params(I->op_begin()+1, I->op_end());
  985. if (Meth == OldVal) { // Changing the function pointer?
  986. const PointerType *NewPTy = cast<PointerType>(NewVal->getType());
  987. const FunctionType *NewTy = cast<FunctionType>(NewPTy->getElementType());
  988. if (NewTy->getReturnType() == Type::VoidTy)
  989. Name = ""; // Make sure not to name a void call!
  990. // Get an iterator to the call instruction so that we can insert casts for
  991. // operands if need be. Note that we do not require operands to be
  992. // convertible, we can insert casts if they are convertible but not
  993. // compatible. The reason for this is that we prefer to have resolved
  994. // functions but casted arguments if possible.
  995. //
  996. BasicBlock::iterator It = I;
  997. // Convert over all of the call operands to their new types... but only
  998. // convert over the part that is not in the vararg section of the call.
  999. //
  1000. for (unsigned i = 0; i != NewTy->getNumParams(); ++i)
  1001. if (Params[i]->getType() != NewTy->getParamType(i)) {
  1002. // Create a cast to convert it to the right type, we know that this
  1003. // is a lossless cast...
  1004. //
  1005. Params[i] = new CastInst(Params[i], NewTy->getParamType(i),
  1006. "callarg.cast." +
  1007. Params[i]->getName(), It);
  1008. }
  1009. Meth = NewVal; // Update call destination to new value
  1010. } else { // Changing an argument, must be in vararg area
  1011. std::vector<Value*>::iterator OI =
  1012. find(Params.begin(), Params.end(), OldVal);
  1013. assert (OI != Params.end() && "Not using value!");
  1014. *OI = NewVal;
  1015. }
  1016. Res = new CallInst(Meth, Params, Name);
  1017. break;
  1018. }
  1019. default:
  1020. assert(0 && "Expression convertible, but don't know how to convert?");
  1021. return;
  1022. }
  1023. // If the instruction was newly created, insert it into the instruction
  1024. // stream.
  1025. //
  1026. BasicBlock::iterator It = I;
  1027. assert(It != BB->end() && "Instruction not in own basic block??");
  1028. BB->getInstList().insert(It, Res); // Keep It pointing to old instruction
  1029. DEBUG(std::cerr << "COT CREATED: " << (void*)Res << " " << Res
  1030. << "In: " << (void*)I << " " << I << "Out: " << (void*)Res
  1031. << " " << Res);
  1032. // Add the instruction to the expression map
  1033. VMC.ExprMap[I] = Res;
  1034. if (I->getType() != Res->getType())
  1035. ConvertValueToNewType(I, Res, VMC, TD);
  1036. else {
  1037. bool FromStart = true;
  1038. Value::use_iterator UI;
  1039. while (1) {
  1040. if (FromStart) UI = I->use_begin();
  1041. if (UI == I->use_end()) break;
  1042. if (isa<ValueHandle>(*UI)) {
  1043. ++UI;
  1044. FromStart = false;
  1045. } else {
  1046. User *U = *UI;
  1047. if (!FromStart) --UI;
  1048. U->replaceUsesOfWith(I, Res);
  1049. if (!FromStart) ++UI;
  1050. }
  1051. }
  1052. }
  1053. }
  1054. ValueHandle::ValueHandle(ValueMapCache &VMC, Value *V)
  1055. : Instruction(Type::VoidTy, UserOp1, ""), Cache(VMC) {
  1056. //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
  1057. Operands.push_back(Use(V, this));
  1058. }
  1059. ValueHandle::ValueHandle(const ValueHandle &VH)
  1060. : Instruction(Type::VoidTy, UserOp1, ""), Cache(VH.Cache) {
  1061. //DEBUG(std::cerr << "VH AQUIRING: " << (void*)V << " " << V);
  1062. Operands.push_back(Use((Value*)VH.getOperand(0), this));
  1063. }
  1064. static void RecursiveDelete(ValueMapCache &Cache, Instruction *I) {
  1065. if (!I || !I->use_empty()) return;
  1066. assert(I->getParent() && "Inst not in basic block!");
  1067. //DEBUG(std::cerr << "VH DELETING: " << (void*)I << " " << I);
  1068. for (User::op_iterator OI = I->op_begin(), OE = I->op_end();
  1069. OI != OE; ++OI)
  1070. if (Instruction *U = dyn_cast<Instruction>(OI)) {
  1071. *OI = 0;
  1072. RecursiveDelete(Cache, U);
  1073. }
  1074. I->getParent()->getInstList().remove(I);
  1075. Cache.OperandsMapped.erase(I);
  1076. Cache.ExprMap.erase(I);
  1077. delete I;
  1078. }
  1079. ValueHandle::~ValueHandle() {
  1080. if (Operands[0]->hasOneUse()) {
  1081. Value *V = Operands[0];
  1082. Operands[0] = 0; // Drop use!
  1083. // Now we just need to remove the old instruction so we don't get infinite
  1084. // loops. Note that we cannot use DCE because DCE won't remove a store
  1085. // instruction, for example.
  1086. //
  1087. RecursiveDelete(Cache, dyn_cast<Instruction>(V));
  1088. } else {
  1089. //DEBUG(std::cerr << "VH RELEASING: " << (void*)Operands[0].get() << " "
  1090. // << Operands[0]->use_size() << " " << Operands[0]);
  1091. }
  1092. }