Fix multiple-return-value-to-first-class-aggregates autoupgrade to
[oota-llvm.git] / lib / VMCore / AutoUpgrade.cpp
1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the auto-upgrade helper functions 
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/AutoUpgrade.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Function.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include <cstring>
22 using namespace llvm;
23
24
25 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
26   assert(F && "Illegal to upgrade a non-existent Function.");
27
28   // Get the Function's name.
29   const std::string& Name = F->getName();
30
31   // Convenience
32   const FunctionType *FTy = F->getFunctionType();
33
34   // Quickly eliminate it, if it's not a candidate.
35   if (Name.length() <= 8 || Name[0] != 'l' || Name[1] != 'l' || 
36       Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
37     return false;
38
39   Module *M = F->getParent();
40   switch (Name[5]) {
41   default: break;
42   case 'a':
43     // This upgrades the llvm.atomic.lcs, llvm.atomic.las, and llvm.atomic.lss
44     // to their new function name
45     if (Name.compare(5,8,"atomic.l",8) == 0) {
46       if (Name.compare(12,3,"lcs",3) == 0) {
47         std::string::size_type delim = Name.find('.',12);
48         F->setName("llvm.atomic.cmp.swap"+Name.substr(delim));
49         NewFn = F;
50         return true;
51       }
52       else if (Name.compare(12,3,"las",3) == 0) {
53         std::string::size_type delim = Name.find('.',12);
54         F->setName("llvm.atomic.load.add"+Name.substr(delim));
55         NewFn = F;
56         return true;
57       }
58       else if (Name.compare(12,3,"lss",3) == 0) {
59         std::string::size_type delim = Name.find('.',12);
60         F->setName("llvm.atomic.load.sub"+Name.substr(delim));
61         NewFn = F;
62         return true;
63       }
64     }
65     break;
66   case 'b':
67     //  This upgrades the name of the llvm.bswap intrinsic function to only use 
68     //  a single type name for overloading. We only care about the old format
69     //  'llvm.bswap.i*.i*', so check for 'bswap.' and then for there being 
70     //  a '.' after 'bswap.'
71     if (Name.compare(5,6,"bswap.",6) == 0) {
72       std::string::size_type delim = Name.find('.',11);
73       
74       if (delim != std::string::npos) {
75         //  Construct the new name as 'llvm.bswap' + '.i*'
76         F->setName(Name.substr(0,10)+Name.substr(delim));
77         NewFn = F;
78         return true;
79       }
80     }
81     break;
82
83   case 'c':
84     //  We only want to fix the 'llvm.ct*' intrinsics which do not have the 
85     //  correct return type, so we check for the name, and then check if the 
86     //  return type does not match the parameter type.
87     if ( (Name.compare(5,5,"ctpop",5) == 0 ||
88           Name.compare(5,4,"ctlz",4) == 0 ||
89           Name.compare(5,4,"cttz",4) == 0) &&
90         FTy->getReturnType() != FTy->getParamType(0)) {
91       //  We first need to change the name of the old (bad) intrinsic, because 
92       //  its type is incorrect, but we cannot overload that name. We 
93       //  arbitrarily unique it here allowing us to construct a correctly named 
94       //  and typed function below.
95       F->setName("");
96
97       //  Now construct the new intrinsic with the correct name and type. We 
98       //  leave the old function around in order to query its type, whatever it 
99       //  may be, and correctly convert up to the new type.
100       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
101                                                     FTy->getParamType(0),
102                                                     FTy->getParamType(0),
103                                                     (Type *)0));
104       return true;
105     }
106     break;
107
108   case 'p':
109     //  This upgrades the llvm.part.select overloaded intrinsic names to only 
110     //  use one type specifier in the name. We only care about the old format
111     //  'llvm.part.select.i*.i*', and solve as above with bswap.
112     if (Name.compare(5,12,"part.select.",12) == 0) {
113       std::string::size_type delim = Name.find('.',17);
114       
115       if (delim != std::string::npos) {
116         //  Construct a new name as 'llvm.part.select' + '.i*'
117         F->setName(Name.substr(0,16)+Name.substr(delim));
118         NewFn = F;
119         return true;
120       }
121       break;
122     }
123
124     //  This upgrades the llvm.part.set intrinsics similarly as above, however 
125     //  we care about 'llvm.part.set.i*.i*.i*', but only the first two types 
126     //  must match. There is an additional type specifier after these two 
127     //  matching types that we must retain when upgrading.  Thus, we require 
128     //  finding 2 periods, not just one, after the intrinsic name.
129     if (Name.compare(5,9,"part.set.",9) == 0) {
130       std::string::size_type delim = Name.find('.',14);
131
132       if (delim != std::string::npos &&
133           Name.find('.',delim+1) != std::string::npos) {
134         //  Construct a new name as 'llvm.part.select' + '.i*.i*'
135         F->setName(Name.substr(0,13)+Name.substr(delim));
136         NewFn = F;
137         return true;
138       }
139       break;
140     }
141
142     break;
143   case 'x': 
144     // This fixes all MMX shift intrinsic instructions to take a
145     // v1i64 instead of a v2i32 as the second parameter.
146     if (Name.compare(5,10,"x86.mmx.ps",10) == 0 &&
147         (Name.compare(13,4,"psll", 4) == 0 ||
148          Name.compare(13,4,"psra", 4) == 0 ||
149          Name.compare(13,4,"psrl", 4) == 0) && Name[17] != 'i') {
150       
151       const llvm::Type *VT = VectorType::get(IntegerType::get(64), 1);
152       
153       // We don't have to do anything if the parameter already has
154       // the correct type.
155       if (FTy->getParamType(1) == VT)
156         break;
157       
158       //  We first need to change the name of the old (bad) intrinsic, because 
159       //  its type is incorrect, but we cannot overload that name. We 
160       //  arbitrarily unique it here allowing us to construct a correctly named 
161       //  and typed function below.
162       F->setName("");
163
164       assert(FTy->getNumParams() == 2 && "MMX shift intrinsics take 2 args!");
165       
166       //  Now construct the new intrinsic with the correct name and type. We 
167       //  leave the old function around in order to query its type, whatever it 
168       //  may be, and correctly convert up to the new type.
169       NewFn = cast<Function>(M->getOrInsertFunction(Name, 
170                                                     FTy->getReturnType(),
171                                                     FTy->getParamType(0),
172                                                     VT,
173                                                     (Type *)0));
174       return true;
175     } else if (Name.compare(5,17,"x86.sse2.loadh.pd",17) == 0 ||
176                Name.compare(5,17,"x86.sse2.loadl.pd",17) == 0 ||
177                Name.compare(5,16,"x86.sse2.movl.dq",16) == 0 ||
178                Name.compare(5,15,"x86.sse2.movs.d",15) == 0 ||
179                Name.compare(5,16,"x86.sse2.shuf.pd",16) == 0 ||
180                Name.compare(5,18,"x86.sse2.unpckh.pd",18) == 0 ||
181                Name.compare(5,18,"x86.sse2.unpckl.pd",18) == 0 ||
182                Name.compare(5,20,"x86.sse2.punpckh.qdq",20) == 0 ||
183                Name.compare(5,20,"x86.sse2.punpckl.qdq",20) == 0) {
184       // Calls to these intrinsics are transformed into ShuffleVector's.
185       NewFn = 0;
186       return true;
187     }
188
189     break;
190   }
191
192   //  This may not belong here. This function is effectively being overloaded 
193   //  to both detect an intrinsic which needs upgrading, and to provide the 
194   //  upgraded form of the intrinsic. We should perhaps have two separate 
195   //  functions for this.
196   return false;
197 }
198
199 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
200   NewFn = 0;
201   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
202
203   // Upgrade intrinsic attributes.  This does not change the function.
204   if (NewFn)
205     F = NewFn;
206   if (unsigned id = F->getIntrinsicID(true))
207     F->setParamAttrs(Intrinsic::getParamAttrs((Intrinsic::ID)id));
208   return Upgraded;
209 }
210
211 // UpgradeIntrinsicCall - Upgrade a call to an old intrinsic to be a call the 
212 // upgraded intrinsic. All argument and return casting must be provided in 
213 // order to seamlessly integrate with existing context.
214 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
215   Function *F = CI->getCalledFunction();
216   assert(F && "CallInst has no function associated with it.");
217
218   if (!NewFn) {
219     bool isLoadH = false, isLoadL = false, isMovL = false;
220     bool isMovSD = false, isShufPD = false;
221     bool isUnpckhPD = false, isUnpcklPD = false;
222     bool isPunpckhQPD = false, isPunpcklQPD = false;
223     if (strcmp(F->getNameStart(), "llvm.x86.sse2.loadh.pd") == 0)
224       isLoadH = true;
225     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.loadl.pd") == 0)
226       isLoadL = true;
227     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.movl.dq") == 0)
228       isMovL = true;
229     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.movs.d") == 0)
230       isMovSD = true;
231     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.shuf.pd") == 0)
232       isShufPD = true;
233     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.unpckh.pd") == 0)
234       isUnpckhPD = true;
235     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.unpckl.pd") == 0)
236       isUnpcklPD = true;
237     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.punpckh.qdq") == 0)
238       isPunpckhQPD = true;
239     else if (strcmp(F->getNameStart(), "llvm.x86.sse2.punpckl.qdq") == 0)
240       isPunpcklQPD = true;
241
242     if (isLoadH || isLoadL || isMovL || isMovSD || isShufPD ||
243         isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
244       std::vector<Constant*> Idxs;
245       Value *Op0 = CI->getOperand(1);
246       ShuffleVectorInst *SI = NULL;
247       if (isLoadH || isLoadL) {
248         Value *Op1 = UndefValue::get(Op0->getType());
249         Value *Addr = new BitCastInst(CI->getOperand(2), 
250                                       PointerType::getUnqual(Type::DoubleTy),
251                                       "upgraded.", CI);
252         Value *Load = new LoadInst(Addr, "upgraded.", false, 8, CI);
253         Value *Idx = ConstantInt::get(Type::Int32Ty, 0);
254         Op1 = InsertElementInst::Create(Op1, Load, Idx, "upgraded.", CI);
255
256         if (isLoadH) {
257           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 0));
258           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
259         } else {
260           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
261           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 1));
262         }
263         Value *Mask = ConstantVector::get(Idxs);
264         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
265       } else if (isMovL) {
266         Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
267         Idxs.push_back(Zero);
268         Idxs.push_back(Zero);
269         Idxs.push_back(Zero);
270         Idxs.push_back(Zero);
271         Value *ZeroV = ConstantVector::get(Idxs);
272
273         Idxs.clear(); 
274         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 4));
275         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 5));
276         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
277         Idxs.push_back(ConstantInt::get(Type::Int32Ty, 3));
278         Value *Mask = ConstantVector::get(Idxs);
279         SI = new ShuffleVectorInst(ZeroV, Op0, Mask, "upgraded.", CI);
280       } else if (isMovSD ||
281                  isUnpckhPD || isUnpcklPD || isPunpckhQPD || isPunpcklQPD) {
282         Value *Op1 = CI->getOperand(2);
283         if (isMovSD) {
284           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
285           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 1));
286         } else if (isUnpckhPD || isPunpckhQPD) {
287           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 1));
288           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 3));
289         } else {
290           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 0));
291           Idxs.push_back(ConstantInt::get(Type::Int32Ty, 2));
292         }
293         Value *Mask = ConstantVector::get(Idxs);
294         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
295       } else if (isShufPD) {
296         Value *Op1 = CI->getOperand(2);
297         unsigned MaskVal = cast<ConstantInt>(CI->getOperand(3))->getZExtValue();
298         Idxs.push_back(ConstantInt::get(Type::Int32Ty, MaskVal & 1));
299         Idxs.push_back(ConstantInt::get(Type::Int32Ty, ((MaskVal >> 1) & 1)+2));
300         Value *Mask = ConstantVector::get(Idxs);
301         SI = new ShuffleVectorInst(Op0, Op1, Mask, "upgraded.", CI);
302       }
303
304       assert(SI && "Unexpected!");
305
306       // Handle any uses of the old CallInst.
307       if (!CI->use_empty())
308         //  Replace all uses of the old call with the new cast which has the 
309         //  correct type.
310         CI->replaceAllUsesWith(SI);
311       
312       //  Clean up the old call now that it has been completely upgraded.
313       CI->eraseFromParent();
314     } else {
315       assert(0 && "Unknown function for CallInst upgrade.");
316     }
317     return;
318   }
319
320   switch (NewFn->getIntrinsicID()) {
321   default:  assert(0 && "Unknown function for CallInst upgrade.");
322   case Intrinsic::x86_mmx_psll_d:
323   case Intrinsic::x86_mmx_psll_q:
324   case Intrinsic::x86_mmx_psll_w:
325   case Intrinsic::x86_mmx_psra_d:
326   case Intrinsic::x86_mmx_psra_w:
327   case Intrinsic::x86_mmx_psrl_d:
328   case Intrinsic::x86_mmx_psrl_q:
329   case Intrinsic::x86_mmx_psrl_w: {
330     Value *Operands[2];
331     
332     Operands[0] = CI->getOperand(1);
333     
334     // Cast the second parameter to the correct type.
335     BitCastInst *BC = new BitCastInst(CI->getOperand(2), 
336                                       NewFn->getFunctionType()->getParamType(1),
337                                       "upgraded.", CI);
338     Operands[1] = BC;
339     
340     //  Construct a new CallInst
341     CallInst *NewCI = CallInst::Create(NewFn, Operands, Operands+2, 
342                                        "upgraded."+CI->getName(), CI);
343     NewCI->setTailCall(CI->isTailCall());
344     NewCI->setCallingConv(CI->getCallingConv());
345     
346     //  Handle any uses of the old CallInst.
347     if (!CI->use_empty())
348       //  Replace all uses of the old call with the new cast which has the 
349       //  correct type.
350       CI->replaceAllUsesWith(NewCI);
351     
352     //  Clean up the old call now that it has been completely upgraded.
353     CI->eraseFromParent();
354     break;
355   }        
356   case Intrinsic::ctlz:
357   case Intrinsic::ctpop:
358   case Intrinsic::cttz: {
359     //  Build a small vector of the 1..(N-1) operands, which are the 
360     //  parameters.
361     SmallVector<Value*, 8> Operands(CI->op_begin()+1, CI->op_end());
362
363     //  Construct a new CallInst
364     CallInst *NewCI = CallInst::Create(NewFn, Operands.begin(), Operands.end(),
365                                        "upgraded."+CI->getName(), CI);
366     NewCI->setTailCall(CI->isTailCall());
367     NewCI->setCallingConv(CI->getCallingConv());
368
369     //  Handle any uses of the old CallInst.
370     if (!CI->use_empty()) {
371       //  Check for sign extend parameter attributes on the return values.
372       bool SrcSExt = NewFn->getParamAttrs().paramHasAttr(0, ParamAttr::SExt);
373       bool DestSExt = F->getParamAttrs().paramHasAttr(0, ParamAttr::SExt);
374       
375       //  Construct an appropriate cast from the new return type to the old.
376       CastInst *RetCast = CastInst::Create(
377                             CastInst::getCastOpcode(NewCI, SrcSExt,
378                                                     F->getReturnType(),
379                                                     DestSExt),
380                             NewCI, F->getReturnType(),
381                             NewCI->getName(), CI);
382       NewCI->moveBefore(RetCast);
383
384       //  Replace all uses of the old call with the new cast which has the 
385       //  correct type.
386       CI->replaceAllUsesWith(RetCast);
387     }
388
389     //  Clean up the old call now that it has been completely upgraded.
390     CI->eraseFromParent();
391   }
392   break;
393   }
394 }
395
396 // This tests each Function to determine if it needs upgrading. When we find 
397 // one we are interested in, we then upgrade all calls to reflect the new 
398 // function.
399 void llvm::UpgradeCallsToIntrinsic(Function* F) {
400   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
401
402   // Upgrade the function and check if it is a totaly new function.
403   Function* NewFn;
404   if (UpgradeIntrinsicFunction(F, NewFn)) {
405     if (NewFn != F) {
406       // Replace all uses to the old function with the new one if necessary.
407       for (Value::use_iterator UI = F->use_begin(), UE = F->use_end();
408            UI != UE; ) {
409         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
410           UpgradeIntrinsicCall(CI, NewFn);
411       }
412       // Remove old function, no longer used, from the module.
413       F->eraseFromParent();
414     }
415   }
416 }
417
418 /// This is an auto-upgrade hook for mutiple-value return statements.
419 /// This function auto-upgrades all such return statements in the given
420 /// function to use aggregate return values built with insertvalue
421 /// instructions.
422 void llvm::UpgradeMultipleReturnValues(Function *CurrentFunction) {
423   const Type *ReturnType = CurrentFunction->getReturnType();
424   for (Function::iterator I = CurrentFunction->begin(),
425        E = CurrentFunction->end(); I != E; ++I) {
426     BasicBlock *BB = I;
427     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
428       unsigned NumVals = RI->getNumOperands();
429       if (NumVals > 1 ||
430           (isa<StructType>(ReturnType) &&
431            (NumVals == 0 || RI->getOperand(0)->getType() != ReturnType))) {
432         std::vector<const Type *> Types(NumVals);
433         for (unsigned i = 0; i != NumVals; ++i)
434           Types[i] = RI->getOperand(i)->getType();
435         const Type *ReturnType = StructType::get(Types);
436         Value *RV = UndefValue::get(ReturnType);
437         for (unsigned i = 0; i != NumVals; ++i)
438           RV = InsertValueInst::Create(RV, RI->getOperand(i), i, "mrv", RI);
439         ReturnInst::Create(RV, RI);
440         RI->eraseFromParent();
441       }
442     }
443   }
444 }