blob: 211934f368a0978a3d9c2bc770413af58da904fd [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
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 bison parser for LLVM assembly languages files.
11//
12//===----------------------------------------------------------------------===//
13
14%{
15#include "UpgradeInternals.h"
16#include "llvm/CallingConv.h"
17#include "llvm/InlineAsm.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/ParameterAttributes.h"
21#include "llvm/ValueSymbolTable.h"
22#include "llvm/Support/GetElementPtrTypeIterator.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/MathExtras.h"
25#include <algorithm>
26#include <iostream>
27#include <map>
28#include <list>
29#include <utility>
30
31// DEBUG_UPREFS - Define this symbol if you want to enable debugging output
32// relating to upreferences in the input stream.
33//
34//#define DEBUG_UPREFS 1
35#ifdef DEBUG_UPREFS
36#define UR_OUT(X) std::cerr << X
37#else
38#define UR_OUT(X)
39#endif
40
41#define YYERROR_VERBOSE 1
42#define YYINCLUDED_STDLIB_H
43#define YYDEBUG 1
44
45int yylex();
46int yyparse();
47
48int yyerror(const char*);
49static void warning(const std::string& WarningMsg);
50
51namespace llvm {
52
53std::istream* LexInput;
54static std::string CurFilename;
55
56// This bool controls whether attributes are ever added to function declarations
57// definitions and calls.
58static bool AddAttributes = false;
59
60static Module *ParserResult;
61static bool ObsoleteVarArgs;
62static bool NewVarArgs;
63static BasicBlock *CurBB;
64static GlobalVariable *CurGV;
65static unsigned lastCallingConv;
66
67// This contains info used when building the body of a function. It is
68// destroyed when the function is completed.
69//
70typedef std::vector<Value *> ValueList; // Numbered defs
71
72typedef std::pair<std::string,TypeInfo> RenameMapKey;
73typedef std::map<RenameMapKey,std::string> RenameMapType;
74
75static void
76ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
77 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
78
79static struct PerModuleInfo {
80 Module *CurrentModule;
81 std::map<const Type *, ValueList> Values; // Module level numbered definitions
82 std::map<const Type *,ValueList> LateResolveValues;
83 std::vector<PATypeHolder> Types;
84 std::vector<Signedness> TypeSigns;
85 std::map<std::string,Signedness> NamedTypeSigns;
86 std::map<std::string,Signedness> NamedValueSigns;
87 std::map<ValID, PATypeHolder> LateResolveTypes;
88 static Module::Endianness Endian;
89 static Module::PointerSize PointerSize;
90 RenameMapType RenameMap;
91
92 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
93 /// how they were referenced and on which line of the input they came from so
94 /// that we can resolve them later and print error messages as appropriate.
95 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
96
97 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
98 // references to global values. Global values may be referenced before they
99 // are defined, and if so, the temporary object that they represent is held
100 // here. This is used for forward references of GlobalValues.
101 //
102 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
103 GlobalRefsType;
104 GlobalRefsType GlobalRefs;
105
106 void ModuleDone() {
107 // If we could not resolve some functions at function compilation time
108 // (calls to functions before they are defined), resolve them now... Types
109 // are resolved when the constant pool has been completely parsed.
110 //
111 ResolveDefinitions(LateResolveValues);
112
113 // Check to make sure that all global value forward references have been
114 // resolved!
115 //
116 if (!GlobalRefs.empty()) {
117 std::string UndefinedReferences = "Unresolved global references exist:\n";
118
119 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
120 I != E; ++I) {
121 UndefinedReferences += " " + I->first.first->getDescription() + " " +
122 I->first.second.getName() + "\n";
123 }
124 error(UndefinedReferences);
125 return;
126 }
127
128 if (CurrentModule->getDataLayout().empty()) {
129 std::string dataLayout;
130 if (Endian != Module::AnyEndianness)
131 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
132 if (PointerSize != Module::AnyPointerSize) {
133 if (!dataLayout.empty())
134 dataLayout += "-";
135 dataLayout.append(PointerSize == Module::Pointer64 ?
136 "p:64:64" : "p:32:32");
137 }
138 CurrentModule->setDataLayout(dataLayout);
139 }
140
141 Values.clear(); // Clear out function local definitions
142 Types.clear();
143 TypeSigns.clear();
144 NamedTypeSigns.clear();
145 NamedValueSigns.clear();
146 CurrentModule = 0;
147 }
148
149 // GetForwardRefForGlobal - Check to see if there is a forward reference
150 // for this global. If so, remove it from the GlobalRefs map and return it.
151 // If not, just return null.
152 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
153 // Check to see if there is a forward reference to this global variable...
154 // if there is, eliminate it and patch the reference to use the new def'n.
155 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
156 GlobalValue *Ret = 0;
157 if (I != GlobalRefs.end()) {
158 Ret = I->second;
159 GlobalRefs.erase(I);
160 }
161 return Ret;
162 }
163 void setEndianness(Module::Endianness E) { Endian = E; }
164 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
165} CurModule;
166
167Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
168Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
169
170static struct PerFunctionInfo {
171 Function *CurrentFunction; // Pointer to current function being created
172
173 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
174 std::map<const Type*, ValueList> LateResolveValues;
175 bool isDeclare; // Is this function a forward declararation?
176 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
177
178 /// BBForwardRefs - When we see forward references to basic blocks, keep
179 /// track of them here.
180 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
181 std::vector<BasicBlock*> NumberedBlocks;
182 RenameMapType RenameMap;
183 unsigned NextBBNum;
184
185 inline PerFunctionInfo() {
186 CurrentFunction = 0;
187 isDeclare = false;
188 Linkage = GlobalValue::ExternalLinkage;
189 }
190
191 inline void FunctionStart(Function *M) {
192 CurrentFunction = M;
193 NextBBNum = 0;
194 }
195
196 void FunctionDone() {
197 NumberedBlocks.clear();
198
199 // Any forward referenced blocks left?
200 if (!BBForwardRefs.empty()) {
201 error("Undefined reference to label " +
202 BBForwardRefs.begin()->first->getName());
203 return;
204 }
205
206 // Resolve all forward references now.
207 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
208
209 Values.clear(); // Clear out function local definitions
210 RenameMap.clear();
211 CurrentFunction = 0;
212 isDeclare = false;
213 Linkage = GlobalValue::ExternalLinkage;
214 }
215} CurFun; // Info for the current function...
216
217static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
218
219/// This function is just a utility to make a Key value for the rename map.
220/// The Key is a combination of the name, type, Signedness of the original
221/// value (global/function). This just constructs the key and ensures that
222/// named Signedness values are resolved to the actual Signedness.
223/// @brief Make a key for the RenameMaps
224static RenameMapKey makeRenameMapKey(const std::string &Name, const Type* Ty,
225 const Signedness &Sign) {
226 TypeInfo TI;
227 TI.T = Ty;
228 if (Sign.isNamed())
229 // Don't allow Named Signedness nodes because they won't match. The actual
230 // Signedness must be looked up in the NamedTypeSigns map.
231 TI.S.copy(CurModule.NamedTypeSigns[Sign.getName()]);
232 else
233 TI.S.copy(Sign);
234 return std::make_pair(Name, TI);
235}
236
237
238//===----------------------------------------------------------------------===//
239// Code to handle definitions of all the types
240//===----------------------------------------------------------------------===//
241
242static int InsertValue(Value *V,
243 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
244 if (V->hasName()) return -1; // Is this a numbered definition?
245
246 // Yes, insert the value into the value table...
247 ValueList &List = ValueTab[V->getType()];
248 List.push_back(V);
249 return List.size()-1;
250}
251
252static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
253 switch (D.Type) {
254 case ValID::NumberVal: // Is it a numbered definition?
255 // Module constants occupy the lowest numbered slots...
256 if ((unsigned)D.Num < CurModule.Types.size()) {
257 return CurModule.Types[(unsigned)D.Num];
258 }
259 break;
260 case ValID::NameVal: // Is it a named definition?
261 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
262 return N;
263 }
264 break;
265 default:
266 error("Internal parser error: Invalid symbol type reference");
267 return 0;
268 }
269
270 // If we reached here, we referenced either a symbol that we don't know about
271 // or an id number that hasn't been read yet. We may be referencing something
272 // forward, so just create an entry to be resolved later and get to it...
273 //
274 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
275
276 if (inFunctionScope()) {
277 if (D.Type == ValID::NameVal) {
278 error("Reference to an undefined type: '" + D.getName() + "'");
279 return 0;
280 } else {
281 error("Reference to an undefined type: #" + itostr(D.Num));
282 return 0;
283 }
284 }
285
286 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
287 if (I != CurModule.LateResolveTypes.end())
288 return I->second;
289
290 Type *Typ = OpaqueType::get();
291 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
292 return Typ;
293}
294
295/// This is like the getType method except that instead of looking up the type
296/// for a given ID, it looks up that type's sign.
297/// @brief Get the signedness of a referenced type
298static Signedness getTypeSign(const ValID &D) {
299 switch (D.Type) {
300 case ValID::NumberVal: // Is it a numbered definition?
301 // Module constants occupy the lowest numbered slots...
302 if ((unsigned)D.Num < CurModule.TypeSigns.size()) {
303 return CurModule.TypeSigns[(unsigned)D.Num];
304 }
305 break;
306 case ValID::NameVal: { // Is it a named definition?
307 std::map<std::string,Signedness>::const_iterator I =
308 CurModule.NamedTypeSigns.find(D.Name);
309 if (I != CurModule.NamedTypeSigns.end())
310 return I->second;
311 // Perhaps its a named forward .. just cache the name
312 Signedness S;
313 S.makeNamed(D.Name);
314 return S;
315 }
316 default:
317 break;
318 }
319 // If we don't find it, its signless
320 Signedness S;
321 S.makeSignless();
322 return S;
323}
324
325/// This function is analagous to getElementType in LLVM. It provides the same
326/// function except that it looks up the Signedness instead of the type. This is
327/// used when processing GEP instructions that need to extract the type of an
328/// indexed struct/array/ptr member.
329/// @brief Look up an element's sign.
330static Signedness getElementSign(const ValueInfo& VI,
331 const std::vector<Value*> &Indices) {
332 const Type *Ptr = VI.V->getType();
333 assert(isa<PointerType>(Ptr) && "Need pointer type");
334
335 unsigned CurIdx = 0;
336 Signedness S(VI.S);
337 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
338 if (CurIdx == Indices.size())
339 break;
340
341 Value *Index = Indices[CurIdx++];
342 assert(!isa<PointerType>(CT) || CurIdx == 1 && "Invalid type");
343 Ptr = CT->getTypeAtIndex(Index);
344 if (const Type* Ty = Ptr->getForwardedType())
345 Ptr = Ty;
346 assert(S.isComposite() && "Bad Signedness type");
347 if (isa<StructType>(CT)) {
348 S = S.get(cast<ConstantInt>(Index)->getZExtValue());
349 } else {
350 S = S.get(0UL);
351 }
352 if (S.isNamed())
353 S = CurModule.NamedTypeSigns[S.getName()];
354 }
355 Signedness Result;
356 Result.makeComposite(S);
357 return Result;
358}
359
360/// This function just translates a ConstantInfo into a ValueInfo and calls
361/// getElementSign(ValueInfo,...). Its just a convenience.
362/// @brief ConstantInfo version of getElementSign.
363static Signedness getElementSign(const ConstInfo& CI,
364 const std::vector<Constant*> &Indices) {
365 ValueInfo VI;
366 VI.V = CI.C;
367 VI.S.copy(CI.S);
368 std::vector<Value*> Idx;
369 for (unsigned i = 0; i < Indices.size(); ++i)
370 Idx.push_back(Indices[i]);
371 Signedness result = getElementSign(VI, Idx);
372 VI.destroy();
373 return result;
374}
375
376/// This function determines if two function types differ only in their use of
377/// the sret parameter attribute in the first argument. If they are identical
378/// in all other respects, it returns true. Otherwise, it returns false.
379static bool FuncTysDifferOnlyBySRet(const FunctionType *F1,
380 const FunctionType *F2) {
381 if (F1->getReturnType() != F2->getReturnType() ||
382 F1->getNumParams() != F2->getNumParams())
383 return false;
384 const ParamAttrsList *PAL1 = F1->getParamAttrs();
385 const ParamAttrsList *PAL2 = F2->getParamAttrs();
386 if (PAL1 && !PAL2 || PAL2 && !PAL1)
387 return false;
388 if (PAL1 && PAL2 && ((PAL1->size() != PAL2->size()) ||
389 (PAL1->getParamAttrs(0) != PAL2->getParamAttrs(0))))
390 return false;
391 unsigned SRetMask = ~unsigned(ParamAttr::StructRet);
392 for (unsigned i = 0; i < F1->getNumParams(); ++i) {
393 if (F1->getParamType(i) != F2->getParamType(i) || (PAL1 && PAL2 &&
394 (unsigned(PAL1->getParamAttrs(i+1)) & SRetMask !=
395 unsigned(PAL2->getParamAttrs(i+1)) & SRetMask)))
396 return false;
397 }
398 return true;
399}
400
401/// This function determines if the type of V and Ty differ only by the SRet
402/// parameter attribute. This is a more generalized case of
403/// FuncTysDIfferOnlyBySRet since it doesn't require FunctionType arguments.
404static bool TypesDifferOnlyBySRet(Value *V, const Type* Ty) {
405 if (V->getType() == Ty)
406 return true;
407 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
408 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
409 if (PF1 && PF2) {
410 const FunctionType* FT1 = dyn_cast<FunctionType>(PF1->getElementType());
411 const FunctionType* FT2 = dyn_cast<FunctionType>(PF2->getElementType());
412 if (FT1 && FT2)
413 return FuncTysDifferOnlyBySRet(FT1, FT2);
414 }
415 return false;
416}
417
418// The upgrade of csretcc to sret param attribute may have caused a function
419// to not be found because the param attribute changed the type of the called
420// function. This helper function, used in getExistingValue, detects that
421// situation and bitcasts the function to the correct type.
422static Value* handleSRetFuncTypeMerge(Value *V, const Type* Ty) {
423 // Handle degenerate cases
424 if (!V)
425 return 0;
426 if (V->getType() == Ty)
427 return V;
428
429 const PointerType *PF1 = dyn_cast<PointerType>(Ty);
430 const PointerType *PF2 = dyn_cast<PointerType>(V->getType());
431 if (PF1 && PF2) {
432 const FunctionType *FT1 = dyn_cast<FunctionType>(PF1->getElementType());
433 const FunctionType *FT2 = dyn_cast<FunctionType>(PF2->getElementType());
434 if (FT1 && FT2 && FuncTysDifferOnlyBySRet(FT1, FT2)) {
435 const ParamAttrsList *PAL2 = FT2->getParamAttrs();
436 if (PAL2 && PAL2->paramHasAttr(1, ParamAttr::StructRet))
437 return V;
438 else if (Constant *C = dyn_cast<Constant>(V))
439 return ConstantExpr::getBitCast(C, PF1);
440 else
441 return new BitCastInst(V, PF1, "upgrd.cast", CurBB);
442 }
443
444 }
445 return 0;
446}
447
448// getExistingValue - Look up the value specified by the provided type and
449// the provided ValID. If the value exists and has already been defined, return
450// it. Otherwise return null.
451//
452static Value *getExistingValue(const Type *Ty, const ValID &D) {
453 if (isa<FunctionType>(Ty)) {
454 error("Functions are not values and must be referenced as pointers");
455 }
456
457 switch (D.Type) {
458 case ValID::NumberVal: { // Is it a numbered definition?
459 unsigned Num = (unsigned)D.Num;
460
461 // Module constants occupy the lowest numbered slots...
462 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
463 if (VI != CurModule.Values.end()) {
464 if (Num < VI->second.size())
465 return VI->second[Num];
466 Num -= VI->second.size();
467 }
468
469 // Make sure that our type is within bounds
470 VI = CurFun.Values.find(Ty);
471 if (VI == CurFun.Values.end()) return 0;
472
473 // Check that the number is within bounds...
474 if (VI->second.size() <= Num) return 0;
475
476 return VI->second[Num];
477 }
478
479 case ValID::NameVal: { // Is it a named definition?
480 // Get the name out of the ID
481 RenameMapKey Key = makeRenameMapKey(D.Name, Ty, D.S);
482 Value *V = 0;
483 if (inFunctionScope()) {
484 // See if the name was renamed
485 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
486 std::string LookupName;
487 if (I != CurFun.RenameMap.end())
488 LookupName = I->second;
489 else
490 LookupName = D.Name;
491 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
492 V = SymTab.lookup(LookupName);
493 if (V && V->getType() != Ty)
494 V = handleSRetFuncTypeMerge(V, Ty);
495 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type");
496 }
497 if (!V) {
498 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
499 std::string LookupName;
500 if (I != CurModule.RenameMap.end())
501 LookupName = I->second;
502 else
503 LookupName = D.Name;
504 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
505 if (V && V->getType() != Ty)
506 V = handleSRetFuncTypeMerge(V, Ty);
507 assert((!V || TypesDifferOnlyBySRet(V, Ty)) && "Found wrong type");
508 }
509 if (!V)
510 return 0;
511
512 D.destroy(); // Free old strdup'd memory...
513 return V;
514 }
515
516 // Check to make sure that "Ty" is an integral type, and that our
517 // value will fit into the specified type...
518 case ValID::ConstSIntVal: // Is it a constant pool reference??
519 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
520 error("Signed integral constant '" + itostr(D.ConstPool64) +
521 "' is invalid for type '" + Ty->getDescription() + "'");
522 }
523 return ConstantInt::get(Ty, D.ConstPool64);
524
525 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
526 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
527 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
528 error("Integral constant '" + utostr(D.UConstPool64) +
529 "' is invalid or out of range");
530 else // This is really a signed reference. Transmogrify.
531 return ConstantInt::get(Ty, D.ConstPool64);
532 } else
533 return ConstantInt::get(Ty, D.UConstPool64);
534
535 case ValID::ConstFPVal: // Is it a floating point const pool reference?
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000536 if (!ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 error("FP constant invalid for type");
Dale Johannesenb9de9f02007-09-06 18:13:44 +0000538 // Lexer has no type info, so builds all FP constants as double.
539 // Fix this here.
540 if (Ty==Type::FloatTy)
541 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
542 return ConstantFP::get(Ty, *D.ConstPoolFP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543
544 case ValID::ConstNullVal: // Is it a null value?
545 if (!isa<PointerType>(Ty))
546 error("Cannot create a a non pointer null");
547 return ConstantPointerNull::get(cast<PointerType>(Ty));
548
549 case ValID::ConstUndefVal: // Is it an undef value?
550 return UndefValue::get(Ty);
551
552 case ValID::ConstZeroVal: // Is it a zero value?
553 return Constant::getNullValue(Ty);
554
555 case ValID::ConstantVal: // Fully resolved constant?
556 if (D.ConstantValue->getType() != Ty)
557 error("Constant expression type different from required type");
558 return D.ConstantValue;
559
560 case ValID::InlineAsmVal: { // Inline asm expression
561 const PointerType *PTy = dyn_cast<PointerType>(Ty);
562 const FunctionType *FTy =
563 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
564 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
565 error("Invalid type for asm constraint string");
566 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
567 D.IAD->HasSideEffects);
568 D.destroy(); // Free InlineAsmDescriptor.
569 return IA;
570 }
571 default:
572 assert(0 && "Unhandled case");
573 return 0;
574 } // End of switch
575
576 assert(0 && "Unhandled case");
577 return 0;
578}
579
580// getVal - This function is identical to getExistingValue, except that if a
581// value is not already defined, it "improvises" by creating a placeholder var
582// that looks and acts just like the requested variable. When the value is
583// defined later, all uses of the placeholder variable are replaced with the
584// real thing.
585//
586static Value *getVal(const Type *Ty, const ValID &ID) {
587 if (Ty == Type::LabelTy)
588 error("Cannot use a basic block here");
589
590 // See if the value has already been defined.
591 Value *V = getExistingValue(Ty, ID);
592 if (V) return V;
593
594 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
595 error("Invalid use of a composite type");
596
597 // If we reached here, we referenced either a symbol that we don't know about
598 // or an id number that hasn't been read yet. We may be referencing something
599 // forward, so just create an entry to be resolved later and get to it...
600 V = new Argument(Ty);
601
602 // Remember where this forward reference came from. FIXME, shouldn't we try
603 // to recycle these things??
604 CurModule.PlaceHolderInfo.insert(
605 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
606
607 if (inFunctionScope())
608 InsertValue(V, CurFun.LateResolveValues);
609 else
610 InsertValue(V, CurModule.LateResolveValues);
611 return V;
612}
613
614/// @brief This just makes any name given to it unique, up to MAX_UINT times.
615static std::string makeNameUnique(const std::string& Name) {
616 static unsigned UniqueNameCounter = 1;
617 std::string Result(Name);
618 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
619 return Result;
620}
621
622/// getBBVal - This is used for two purposes:
623/// * If isDefinition is true, a new basic block with the specified ID is being
624/// defined.
625/// * If isDefinition is true, this is a reference to a basic block, which may
626/// or may not be a forward reference.
627///
628static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
629 assert(inFunctionScope() && "Can't get basic block at global scope");
630
631 std::string Name;
632 BasicBlock *BB = 0;
633 switch (ID.Type) {
634 default:
635 error("Illegal label reference " + ID.getName());
636 break;
637 case ValID::NumberVal: // Is it a numbered definition?
638 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
639 CurFun.NumberedBlocks.resize(ID.Num+1);
640 BB = CurFun.NumberedBlocks[ID.Num];
641 break;
642 case ValID::NameVal: // Is it a named definition?
643 Name = ID.Name;
644 if (Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name)) {
645 if (N->getType() != Type::LabelTy) {
646 // Register names didn't use to conflict with basic block names
647 // because of type planes. Now they all have to be unique. So, we just
648 // rename the register and treat this name as if no basic block
649 // had been found.
650 RenameMapKey Key = makeRenameMapKey(ID.Name, N->getType(), ID.S);
651 N->setName(makeNameUnique(N->getName()));
652 CurModule.RenameMap[Key] = N->getName();
653 BB = 0;
654 } else {
655 BB = cast<BasicBlock>(N);
656 }
657 }
658 break;
659 }
660
661 // See if the block has already been defined.
662 if (BB) {
663 // If this is the definition of the block, make sure the existing value was
664 // just a forward reference. If it was a forward reference, there will be
665 // an entry for it in the PlaceHolderInfo map.
666 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
667 // The existing value was a definition, not a forward reference.
668 error("Redefinition of label " + ID.getName());
669
670 ID.destroy(); // Free strdup'd memory.
671 return BB;
672 }
673
674 // Otherwise this block has not been seen before.
675 BB = new BasicBlock("", CurFun.CurrentFunction);
676 if (ID.Type == ValID::NameVal) {
677 BB->setName(ID.Name);
678 } else {
679 CurFun.NumberedBlocks[ID.Num] = BB;
680 }
681
682 // If this is not a definition, keep track of it so we can use it as a forward
683 // reference.
684 if (!isDefinition) {
685 // Remember where this forward reference came from.
686 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
687 } else {
688 // The forward declaration could have been inserted anywhere in the
689 // function: insert it into the correct place now.
690 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
691 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
692 }
693 ID.destroy();
694 return BB;
695}
696
697
698//===----------------------------------------------------------------------===//
699// Code to handle forward references in instructions
700//===----------------------------------------------------------------------===//
701//
702// This code handles the late binding needed with statements that reference
703// values not defined yet... for example, a forward branch, or the PHI node for
704// a loop body.
705//
706// This keeps a table (CurFun.LateResolveValues) of all such forward references
707// and back patchs after we are done.
708//
709
710// ResolveDefinitions - If we could not resolve some defs at parsing
711// time (forward branches, phi functions for loops, etc...) resolve the
712// defs now...
713//
714static void
715ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
716 std::map<const Type*,ValueList> *FutureLateResolvers) {
717
718 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
719 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
720 E = LateResolvers.end(); LRI != E; ++LRI) {
721 const Type* Ty = LRI->first;
722 ValueList &List = LRI->second;
723 while (!List.empty()) {
724 Value *V = List.back();
725 List.pop_back();
726
727 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
728 CurModule.PlaceHolderInfo.find(V);
729 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
730
731 ValID &DID = PHI->second.first;
732
733 Value *TheRealValue = getExistingValue(Ty, DID);
734 if (TheRealValue) {
735 V->replaceAllUsesWith(TheRealValue);
736 delete V;
737 CurModule.PlaceHolderInfo.erase(PHI);
738 } else if (FutureLateResolvers) {
739 // Functions have their unresolved items forwarded to the module late
740 // resolver table
741 InsertValue(V, *FutureLateResolvers);
742 } else {
743 if (DID.Type == ValID::NameVal) {
744 error("Reference to an invalid definition: '" + DID.getName() +
745 "' of type '" + V->getType()->getDescription() + "'",
746 PHI->second.second);
747 return;
748 } else {
749 error("Reference to an invalid definition: #" +
750 itostr(DID.Num) + " of type '" +
751 V->getType()->getDescription() + "'", PHI->second.second);
752 return;
753 }
754 }
755 }
756 }
757
758 LateResolvers.clear();
759}
760
761/// This function is used for type resolution and upref handling. When a type
762/// becomes concrete, this function is called to adjust the signedness for the
763/// concrete type.
764static void ResolveTypeSign(const Type* oldTy, const Signedness &Sign) {
765 std::string TyName = CurModule.CurrentModule->getTypeName(oldTy);
766 if (!TyName.empty())
767 CurModule.NamedTypeSigns[TyName] = Sign;
768}
769
770/// ResolveTypeTo - A brand new type was just declared. This means that (if
771/// name is not null) things referencing Name can be resolved. Otherwise,
772/// things refering to the number can be resolved. Do this now.
773static void ResolveTypeTo(char *Name, const Type *ToTy, const Signedness& Sign){
774 ValID D;
775 if (Name)
776 D = ValID::create(Name);
777 else
778 D = ValID::create((int)CurModule.Types.size());
779 D.S.copy(Sign);
780
781 if (Name)
782 CurModule.NamedTypeSigns[Name] = Sign;
783
784 std::map<ValID, PATypeHolder>::iterator I =
785 CurModule.LateResolveTypes.find(D);
786 if (I != CurModule.LateResolveTypes.end()) {
787 const Type *OldTy = I->second.get();
788 ((DerivedType*)OldTy)->refineAbstractTypeTo(ToTy);
789 CurModule.LateResolveTypes.erase(I);
790 }
791}
792
793/// This is the implementation portion of TypeHasInteger. It traverses the
794/// type given, avoiding recursive types, and returns true as soon as it finds
795/// an integer type. If no integer type is found, it returns false.
796static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
797 // Handle some easy cases
798 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
799 return false;
800 if (Ty->isInteger())
801 return true;
802 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
803 return STy->getElementType()->isInteger();
804
805 // Avoid type structure recursion
806 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
807 I != E; ++I)
808 if (Ty == *I)
809 return false;
810
811 // Push us on the type stack
812 Stack.push_back(Ty);
813
814 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
815 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
816 return true;
817 FunctionType::param_iterator I = FTy->param_begin();
818 FunctionType::param_iterator E = FTy->param_end();
819 for (; I != E; ++I)
820 if (TypeHasIntegerI(*I, Stack))
821 return true;
822 return false;
823 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
824 StructType::element_iterator I = STy->element_begin();
825 StructType::element_iterator E = STy->element_end();
826 for (; I != E; ++I) {
827 if (TypeHasIntegerI(*I, Stack))
828 return true;
829 }
830 return false;
831 }
832 // There shouldn't be anything else, but its definitely not integer
833 assert(0 && "What type is this?");
834 return false;
835}
836
837/// This is the interface to TypeHasIntegerI. It just provides the type stack,
838/// to avoid recursion, and then calls TypeHasIntegerI.
839static inline bool TypeHasInteger(const Type *Ty) {
840 std::vector<const Type*> TyStack;
841 return TypeHasIntegerI(Ty, TyStack);
842}
843
844// setValueName - Set the specified value to the name given. The name may be
845// null potentially, in which case this is a noop. The string passed in is
846// assumed to be a malloc'd string buffer, and is free'd by this function.
847//
848static void setValueName(const ValueInfo &V, char *NameStr) {
849 if (NameStr) {
850 std::string Name(NameStr); // Copy string
851 free(NameStr); // Free old string
852
853 if (V.V->getType() == Type::VoidTy) {
854 error("Can't assign name '" + Name + "' to value with void type");
855 return;
856 }
857
858 assert(inFunctionScope() && "Must be in function scope");
859
860 // Search the function's symbol table for an existing value of this name
861 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
862 Value* Existing = ST.lookup(Name);
863 if (Existing) {
864 // An existing value of the same name was found. This might have happened
865 // because of the integer type planes collapsing in LLVM 2.0.
866 if (Existing->getType() == V.V->getType() &&
867 !TypeHasInteger(Existing->getType())) {
868 // If the type does not contain any integers in them then this can't be
869 // a type plane collapsing issue. It truly is a redefinition and we
870 // should error out as the assembly is invalid.
871 error("Redefinition of value named '" + Name + "' of type '" +
872 V.V->getType()->getDescription() + "'");
873 return;
874 }
875 // In LLVM 2.0 we don't allow names to be re-used for any values in a
876 // function, regardless of Type. Previously re-use of names was okay as
877 // long as they were distinct types. With type planes collapsing because
878 // of the signedness change and because of PR411, this can no longer be
879 // supported. We must search the entire symbol table for a conflicting
880 // name and make the name unique. No warning is needed as this can't
881 // cause a problem.
882 std::string NewName = makeNameUnique(Name);
883 // We're changing the name but it will probably be used by other
884 // instructions as operands later on. Consequently we have to retain
885 // a mapping of the renaming that we're doing.
886 RenameMapKey Key = makeRenameMapKey(Name, V.V->getType(), V.S);
887 CurFun.RenameMap[Key] = NewName;
888 Name = NewName;
889 }
890
891 // Set the name.
892 V.V->setName(Name);
893 }
894}
895
896/// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
897/// this is a declaration, otherwise it is a definition.
898static GlobalVariable *
899ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
900 bool isConstantGlobal, const Type *Ty,
901 Constant *Initializer,
902 const Signedness &Sign) {
903 if (isa<FunctionType>(Ty))
904 error("Cannot declare global vars of function type");
905
906 const PointerType *PTy = PointerType::get(Ty);
907
908 std::string Name;
909 if (NameStr) {
910 Name = NameStr; // Copy string
911 free(NameStr); // Free old string
912 }
913
914 // See if this global value was forward referenced. If so, recycle the
915 // object.
916 ValID ID;
917 if (!Name.empty()) {
918 ID = ValID::create((char*)Name.c_str());
919 } else {
920 ID = ValID::create((int)CurModule.Values[PTy].size());
921 }
922 ID.S.makeComposite(Sign);
923
924 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
925 // Move the global to the end of the list, from whereever it was
926 // previously inserted.
927 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
928 CurModule.CurrentModule->getGlobalList().remove(GV);
929 CurModule.CurrentModule->getGlobalList().push_back(GV);
930 GV->setInitializer(Initializer);
931 GV->setLinkage(Linkage);
932 GV->setConstant(isConstantGlobal);
933 InsertValue(GV, CurModule.Values);
934 return GV;
935 }
936
937 // If this global has a name, check to see if there is already a definition
938 // of this global in the module and emit warnings if there are conflicts.
939 if (!Name.empty()) {
940 // The global has a name. See if there's an existing one of the same name.
941 if (CurModule.CurrentModule->getNamedGlobal(Name) ||
942 CurModule.CurrentModule->getFunction(Name)) {
943 // We found an existing global of the same name. This isn't allowed
944 // in LLVM 2.0. Consequently, we must alter the name of the global so it
945 // can at least compile. This can happen because of type planes
946 // There is alread a global of the same name which means there is a
947 // conflict. Let's see what we can do about it.
948 std::string NewName(makeNameUnique(Name));
949 if (Linkage != GlobalValue::InternalLinkage) {
950 // The linkage of this gval is external so we can't reliably rename
951 // it because it could potentially create a linking problem.
952 // However, we can't leave the name conflict in the output either or
953 // it won't assemble with LLVM 2.0. So, all we can do is rename
954 // this one to something unique and emit a warning about the problem.
955 warning("Renaming global variable '" + Name + "' to '" + NewName +
956 "' may cause linkage errors");
957 }
958
959 // Put the renaming in the global rename map
960 RenameMapKey Key = makeRenameMapKey(Name, PointerType::get(Ty), ID.S);
961 CurModule.RenameMap[Key] = NewName;
962
963 // Rename it
964 Name = NewName;
965 }
966 }
967
968 // Otherwise there is no existing GV to use, create one now.
969 GlobalVariable *GV =
970 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
971 CurModule.CurrentModule);
972 InsertValue(GV, CurModule.Values);
973 // Remember the sign of this global.
974 CurModule.NamedValueSigns[Name] = ID.S;
975 return GV;
976}
977
978// setTypeName - Set the specified type to the name given. The name may be
979// null potentially, in which case this is a noop. The string passed in is
980// assumed to be a malloc'd string buffer, and is freed by this function.
981//
982// This function returns true if the type has already been defined, but is
983// allowed to be redefined in the specified context. If the name is a new name
984// for the type plane, it is inserted and false is returned.
985static bool setTypeName(const PATypeInfo& TI, char *NameStr) {
986 assert(!inFunctionScope() && "Can't give types function-local names");
987 if (NameStr == 0) return false;
988
989 std::string Name(NameStr); // Copy string
990 free(NameStr); // Free old string
991
992 const Type* Ty = TI.PAT->get();
993
994 // We don't allow assigning names to void type
995 if (Ty == Type::VoidTy) {
996 error("Can't assign name '" + Name + "' to the void type");
997 return false;
998 }
999
1000 // Set the type name, checking for conflicts as we do so.
1001 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, Ty);
1002
1003 // Save the sign information for later use
1004 CurModule.NamedTypeSigns[Name] = TI.S;
1005
1006 if (AlreadyExists) { // Inserting a name that is already defined???
1007 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
1008 assert(Existing && "Conflict but no matching type?");
1009
1010 // There is only one case where this is allowed: when we are refining an
1011 // opaque type. In this case, Existing will be an opaque type.
1012 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
1013 // We ARE replacing an opaque type!
1014 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(Ty);
1015 return true;
1016 }
1017
1018 // Otherwise, this is an attempt to redefine a type. That's okay if
1019 // the redefinition is identical to the original. This will be so if
1020 // Existing and T point to the same Type object. In this one case we
1021 // allow the equivalent redefinition.
1022 if (Existing == Ty) return true; // Yes, it's equal.
1023
1024 // Any other kind of (non-equivalent) redefinition is an error.
1025 error("Redefinition of type named '" + Name + "' in the '" +
1026 Ty->getDescription() + "' type plane");
1027 }
1028
1029 return false;
1030}
1031
1032//===----------------------------------------------------------------------===//
1033// Code for handling upreferences in type names...
1034//
1035
1036// TypeContains - Returns true if Ty directly contains E in it.
1037//
1038static bool TypeContains(const Type *Ty, const Type *E) {
1039 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
1040 E) != Ty->subtype_end();
1041}
1042
1043namespace {
1044 struct UpRefRecord {
1045 // NestingLevel - The number of nesting levels that need to be popped before
1046 // this type is resolved.
1047 unsigned NestingLevel;
1048
1049 // LastContainedTy - This is the type at the current binding level for the
1050 // type. Every time we reduce the nesting level, this gets updated.
1051 const Type *LastContainedTy;
1052
1053 // UpRefTy - This is the actual opaque type that the upreference is
1054 // represented with.
1055 OpaqueType *UpRefTy;
1056
1057 UpRefRecord(unsigned NL, OpaqueType *URTy)
1058 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) { }
1059 };
1060}
1061
1062// UpRefs - A list of the outstanding upreferences that need to be resolved.
1063static std::vector<UpRefRecord> UpRefs;
1064
1065/// HandleUpRefs - Every time we finish a new layer of types, this function is
1066/// called. It loops through the UpRefs vector, which is a list of the
1067/// currently active types. For each type, if the up reference is contained in
1068/// the newly completed type, we decrement the level count. When the level
1069/// count reaches zero, the upreferenced type is the type that is passed in:
1070/// thus we can complete the cycle.
1071///
1072static PATypeHolder HandleUpRefs(const Type *ty, const Signedness& Sign) {
1073 // If Ty isn't abstract, or if there are no up-references in it, then there is
1074 // nothing to resolve here.
1075 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1076
1077 PATypeHolder Ty(ty);
1078 UR_OUT("Type '" << Ty->getDescription() <<
1079 "' newly formed. Resolving upreferences.\n" <<
1080 UpRefs.size() << " upreferences active!\n");
1081
1082 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1083 // to zero), we resolve them all together before we resolve them to Ty. At
1084 // the end of the loop, if there is anything to resolve to Ty, it will be in
1085 // this variable.
1086 OpaqueType *TypeToResolve = 0;
1087
1088 unsigned i = 0;
1089 for (; i != UpRefs.size(); ++i) {
1090 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1091 << UpRefs[i].UpRefTy->getDescription() << ") = "
1092 << (TypeContains(Ty, UpRefs[i].UpRefTy) ? "true" : "false") << "\n");
1093 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
1094 // Decrement level of upreference
1095 unsigned Level = --UpRefs[i].NestingLevel;
1096 UpRefs[i].LastContainedTy = Ty;
1097 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
1098 if (Level == 0) { // Upreference should be resolved!
1099 if (!TypeToResolve) {
1100 TypeToResolve = UpRefs[i].UpRefTy;
1101 } else {
1102 UR_OUT(" * Resolving upreference for "
1103 << UpRefs[i].UpRefTy->getDescription() << "\n";
1104 std::string OldName = UpRefs[i].UpRefTy->getDescription());
1105 ResolveTypeSign(UpRefs[i].UpRefTy, Sign);
1106 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1107 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
1108 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
1109 }
1110 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
1111 --i; // Do not skip the next element...
1112 }
1113 }
1114 }
1115
1116 if (TypeToResolve) {
1117 UR_OUT(" * Resolving upreference for "
1118 << UpRefs[i].UpRefTy->getDescription() << "\n";
1119 std::string OldName = TypeToResolve->getDescription());
1120 ResolveTypeSign(TypeToResolve, Sign);
1121 TypeToResolve->refineAbstractTypeTo(Ty);
1122 }
1123
1124 return Ty;
1125}
1126
1127bool Signedness::operator<(const Signedness &that) const {
1128 if (isNamed()) {
1129 if (that.isNamed())
1130 return *(this->name) < *(that.name);
1131 else
1132 return CurModule.NamedTypeSigns[*name] < that;
1133 } else if (that.isNamed()) {
1134 return *this < CurModule.NamedTypeSigns[*that.name];
1135 }
1136
1137 if (isComposite() && that.isComposite()) {
1138 if (sv->size() == that.sv->size()) {
1139 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1140 SignVector::const_iterator thatI = that.sv->begin(),
1141 thatE = that.sv->end();
1142 for (; thisI != thisE; ++thisI, ++thatI) {
1143 if (*thisI < *thatI)
1144 return true;
1145 else if (!(*thisI == *thatI))
1146 return false;
1147 }
1148 return false;
1149 }
1150 return sv->size() < that.sv->size();
1151 }
1152 return kind < that.kind;
1153}
1154
1155bool Signedness::operator==(const Signedness &that) const {
1156 if (isNamed())
1157 if (that.isNamed())
1158 return *(this->name) == *(that.name);
1159 else
1160 return CurModule.NamedTypeSigns[*(this->name)] == that;
1161 else if (that.isNamed())
1162 return *this == CurModule.NamedTypeSigns[*(that.name)];
1163 if (isComposite() && that.isComposite()) {
1164 if (sv->size() == that.sv->size()) {
1165 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1166 SignVector::const_iterator thatI = that.sv->begin(),
1167 thatE = that.sv->end();
1168 for (; thisI != thisE; ++thisI, ++thatI) {
1169 if (!(*thisI == *thatI))
1170 return false;
1171 }
1172 return true;
1173 }
1174 return false;
1175 }
1176 return kind == that.kind;
1177}
1178
1179void Signedness::copy(const Signedness &that) {
1180 if (that.isNamed()) {
1181 kind = Named;
1182 name = new std::string(*that.name);
1183 } else if (that.isComposite()) {
1184 kind = Composite;
1185 sv = new SignVector();
1186 *sv = *that.sv;
1187 } else {
1188 kind = that.kind;
1189 sv = 0;
1190 }
1191}
1192
1193void Signedness::destroy() {
1194 if (isNamed()) {
1195 delete name;
1196 } else if (isComposite()) {
1197 delete sv;
1198 }
1199}
1200
1201#ifndef NDEBUG
1202void Signedness::dump() const {
1203 if (isComposite()) {
1204 if (sv->size() == 1) {
1205 (*sv)[0].dump();
1206 std::cerr << "*";
1207 } else {
1208 std::cerr << "{ " ;
1209 for (unsigned i = 0; i < sv->size(); ++i) {
1210 if (i != 0)
1211 std::cerr << ", ";
1212 (*sv)[i].dump();
1213 }
1214 std::cerr << "} " ;
1215 }
1216 } else if (isNamed()) {
1217 std::cerr << *name;
1218 } else if (isSigned()) {
1219 std::cerr << "S";
1220 } else if (isUnsigned()) {
1221 std::cerr << "U";
1222 } else
1223 std::cerr << ".";
1224}
1225#endif
1226
1227static inline Instruction::TermOps
1228getTermOp(TermOps op) {
1229 switch (op) {
1230 default : assert(0 && "Invalid OldTermOp");
1231 case RetOp : return Instruction::Ret;
1232 case BrOp : return Instruction::Br;
1233 case SwitchOp : return Instruction::Switch;
1234 case InvokeOp : return Instruction::Invoke;
1235 case UnwindOp : return Instruction::Unwind;
1236 case UnreachableOp: return Instruction::Unreachable;
1237 }
1238}
1239
1240static inline Instruction::BinaryOps
1241getBinaryOp(BinaryOps op, const Type *Ty, const Signedness& Sign) {
1242 switch (op) {
1243 default : assert(0 && "Invalid OldBinaryOps");
1244 case SetEQ :
1245 case SetNE :
1246 case SetLE :
1247 case SetGE :
1248 case SetLT :
1249 case SetGT : assert(0 && "Should use getCompareOp");
1250 case AddOp : return Instruction::Add;
1251 case SubOp : return Instruction::Sub;
1252 case MulOp : return Instruction::Mul;
1253 case DivOp : {
1254 // This is an obsolete instruction so we must upgrade it based on the
1255 // types of its operands.
1256 bool isFP = Ty->isFloatingPoint();
1257 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1258 // If its a vector type we want to use the element type
1259 isFP = PTy->getElementType()->isFloatingPoint();
1260 if (isFP)
1261 return Instruction::FDiv;
1262 else if (Sign.isSigned())
1263 return Instruction::SDiv;
1264 return Instruction::UDiv;
1265 }
1266 case UDivOp : return Instruction::UDiv;
1267 case SDivOp : return Instruction::SDiv;
1268 case FDivOp : return Instruction::FDiv;
1269 case RemOp : {
1270 // This is an obsolete instruction so we must upgrade it based on the
1271 // types of its operands.
1272 bool isFP = Ty->isFloatingPoint();
1273 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1274 // If its a vector type we want to use the element type
1275 isFP = PTy->getElementType()->isFloatingPoint();
1276 // Select correct opcode
1277 if (isFP)
1278 return Instruction::FRem;
1279 else if (Sign.isSigned())
1280 return Instruction::SRem;
1281 return Instruction::URem;
1282 }
1283 case URemOp : return Instruction::URem;
1284 case SRemOp : return Instruction::SRem;
1285 case FRemOp : return Instruction::FRem;
1286 case LShrOp : return Instruction::LShr;
1287 case AShrOp : return Instruction::AShr;
1288 case ShlOp : return Instruction::Shl;
1289 case ShrOp :
1290 if (Sign.isSigned())
1291 return Instruction::AShr;
1292 return Instruction::LShr;
1293 case AndOp : return Instruction::And;
1294 case OrOp : return Instruction::Or;
1295 case XorOp : return Instruction::Xor;
1296 }
1297}
1298
1299static inline Instruction::OtherOps
1300getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1301 const Signedness &Sign) {
1302 bool isSigned = Sign.isSigned();
1303 bool isFP = Ty->isFloatingPoint();
1304 switch (op) {
1305 default : assert(0 && "Invalid OldSetCC");
1306 case SetEQ :
1307 if (isFP) {
1308 predicate = FCmpInst::FCMP_OEQ;
1309 return Instruction::FCmp;
1310 } else {
1311 predicate = ICmpInst::ICMP_EQ;
1312 return Instruction::ICmp;
1313 }
1314 case SetNE :
1315 if (isFP) {
1316 predicate = FCmpInst::FCMP_UNE;
1317 return Instruction::FCmp;
1318 } else {
1319 predicate = ICmpInst::ICMP_NE;
1320 return Instruction::ICmp;
1321 }
1322 case SetLE :
1323 if (isFP) {
1324 predicate = FCmpInst::FCMP_OLE;
1325 return Instruction::FCmp;
1326 } else {
1327 if (isSigned)
1328 predicate = ICmpInst::ICMP_SLE;
1329 else
1330 predicate = ICmpInst::ICMP_ULE;
1331 return Instruction::ICmp;
1332 }
1333 case SetGE :
1334 if (isFP) {
1335 predicate = FCmpInst::FCMP_OGE;
1336 return Instruction::FCmp;
1337 } else {
1338 if (isSigned)
1339 predicate = ICmpInst::ICMP_SGE;
1340 else
1341 predicate = ICmpInst::ICMP_UGE;
1342 return Instruction::ICmp;
1343 }
1344 case SetLT :
1345 if (isFP) {
1346 predicate = FCmpInst::FCMP_OLT;
1347 return Instruction::FCmp;
1348 } else {
1349 if (isSigned)
1350 predicate = ICmpInst::ICMP_SLT;
1351 else
1352 predicate = ICmpInst::ICMP_ULT;
1353 return Instruction::ICmp;
1354 }
1355 case SetGT :
1356 if (isFP) {
1357 predicate = FCmpInst::FCMP_OGT;
1358 return Instruction::FCmp;
1359 } else {
1360 if (isSigned)
1361 predicate = ICmpInst::ICMP_SGT;
1362 else
1363 predicate = ICmpInst::ICMP_UGT;
1364 return Instruction::ICmp;
1365 }
1366 }
1367}
1368
1369static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1370 switch (op) {
1371 default : assert(0 && "Invalid OldMemoryOps");
1372 case MallocOp : return Instruction::Malloc;
1373 case FreeOp : return Instruction::Free;
1374 case AllocaOp : return Instruction::Alloca;
1375 case LoadOp : return Instruction::Load;
1376 case StoreOp : return Instruction::Store;
1377 case GetElementPtrOp : return Instruction::GetElementPtr;
1378 }
1379}
1380
1381static inline Instruction::OtherOps
1382getOtherOp(OtherOps op, const Signedness &Sign) {
1383 switch (op) {
1384 default : assert(0 && "Invalid OldOtherOps");
1385 case PHIOp : return Instruction::PHI;
1386 case CallOp : return Instruction::Call;
1387 case SelectOp : return Instruction::Select;
1388 case UserOp1 : return Instruction::UserOp1;
1389 case UserOp2 : return Instruction::UserOp2;
1390 case VAArg : return Instruction::VAArg;
1391 case ExtractElementOp : return Instruction::ExtractElement;
1392 case InsertElementOp : return Instruction::InsertElement;
1393 case ShuffleVectorOp : return Instruction::ShuffleVector;
1394 case ICmpOp : return Instruction::ICmp;
1395 case FCmpOp : return Instruction::FCmp;
1396 };
1397}
1398
1399static inline Value*
1400getCast(CastOps op, Value *Src, const Signedness &SrcSign, const Type *DstTy,
1401 const Signedness &DstSign, bool ForceInstruction = false) {
1402 Instruction::CastOps Opcode;
1403 const Type* SrcTy = Src->getType();
1404 if (op == CastOp) {
1405 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1406 // fp -> ptr cast is no longer supported but we must upgrade this
1407 // by doing a double cast: fp -> int -> ptr
1408 SrcTy = Type::Int64Ty;
1409 Opcode = Instruction::IntToPtr;
1410 if (isa<Constant>(Src)) {
1411 Src = ConstantExpr::getCast(Instruction::FPToUI,
1412 cast<Constant>(Src), SrcTy);
1413 } else {
1414 std::string NewName(makeNameUnique(Src->getName()));
1415 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1416 }
1417 } else if (isa<IntegerType>(DstTy) &&
1418 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1419 // cast type %x to bool was previously defined as setne type %x, null
1420 // The cast semantic is now to truncate, not compare so we must retain
1421 // the original intent by replacing the cast with a setne
1422 Constant* Null = Constant::getNullValue(SrcTy);
1423 Instruction::OtherOps Opcode = Instruction::ICmp;
1424 unsigned short predicate = ICmpInst::ICMP_NE;
1425 if (SrcTy->isFloatingPoint()) {
1426 Opcode = Instruction::FCmp;
1427 predicate = FCmpInst::FCMP_ONE;
1428 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1429 error("Invalid cast to bool");
1430 }
1431 if (isa<Constant>(Src) && !ForceInstruction)
1432 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1433 else
1434 return CmpInst::create(Opcode, predicate, Src, Null);
1435 }
1436 // Determine the opcode to use by calling CastInst::getCastOpcode
1437 Opcode =
1438 CastInst::getCastOpcode(Src, SrcSign.isSigned(), DstTy,
1439 DstSign.isSigned());
1440
1441 } else switch (op) {
1442 default: assert(0 && "Invalid cast token");
1443 case TruncOp: Opcode = Instruction::Trunc; break;
1444 case ZExtOp: Opcode = Instruction::ZExt; break;
1445 case SExtOp: Opcode = Instruction::SExt; break;
1446 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1447 case FPExtOp: Opcode = Instruction::FPExt; break;
1448 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1449 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1450 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1451 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1452 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1453 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1454 case BitCastOp: Opcode = Instruction::BitCast; break;
1455 }
1456
1457 if (isa<Constant>(Src) && !ForceInstruction)
1458 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1459 return CastInst::create(Opcode, Src, DstTy);
1460}
1461
1462static Instruction *
1463upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1464 std::vector<Value*>& Args) {
1465
1466 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1467 if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' ||
1468 Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
1469 return 0;
1470
1471 switch (Name[5]) {
1472 case 'i':
1473 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1474 if (Args.size() != 2)
1475 error("Invalid prototype for " + Name);
1476 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1477 }
1478 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479
1480 case 'v' : {
1481 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1482 std::vector<const Type*> Params;
1483 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1484 if (Args.size() != 1)
1485 error("Invalid prototype for " + Name + " prototype");
1486 Params.push_back(PtrTy);
1487 const FunctionType *FTy =
1488 FunctionType::get(Type::VoidTy, Params, false);
1489 const PointerType *PFTy = PointerType::get(FTy);
1490 Value* Func = getVal(PFTy, ID);
1491 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
David Greeneb1c4a7b2007-08-01 03:43:44 +00001492 return new CallInst(Func, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001493 } else if (Name == "llvm.va_copy") {
1494 if (Args.size() != 2)
1495 error("Invalid prototype for " + Name + " prototype");
1496 Params.push_back(PtrTy);
1497 Params.push_back(PtrTy);
1498 const FunctionType *FTy =
1499 FunctionType::get(Type::VoidTy, Params, false);
1500 const PointerType *PFTy = PointerType::get(FTy);
1501 Value* Func = getVal(PFTy, ID);
1502 std::string InstName0(makeNameUnique("va0"));
1503 std::string InstName1(makeNameUnique("va1"));
1504 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1505 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
David Greeneb1c4a7b2007-08-01 03:43:44 +00001506 return new CallInst(Func, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001507 }
1508 }
1509 }
1510 return 0;
1511}
1512
1513const Type* upgradeGEPCEIndices(const Type* PTy,
1514 std::vector<ValueInfo> *Indices,
1515 std::vector<Constant*> &Result) {
1516 const Type *Ty = PTy;
1517 Result.clear();
1518 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1519 Constant *Index = cast<Constant>((*Indices)[i].V);
1520
1521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1522 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1523 // struct indices to i32 struct indices with ZExt for compatibility.
1524 if (CI->getBitWidth() < 32)
1525 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1526 }
1527
1528 if (isa<SequentialType>(Ty)) {
1529 // Make sure that unsigned SequentialType indices are zext'd to
1530 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1531 // all indices for SequentialType elements. We must retain the same
1532 // semantic (zext) for unsigned types.
1533 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1534 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1535 Index = ConstantExpr::getCast(Instruction::ZExt, Index,Type::Int64Ty);
1536 }
1537 }
1538 }
1539 Result.push_back(Index);
David Greene393be882007-09-04 15:46:09 +00001540 Ty = GetElementPtrInst::getIndexedType(PTy, Result.begin(),
1541 Result.end(),true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 if (!Ty)
1543 error("Index list invalid for constant getelementptr");
1544 }
1545 return Ty;
1546}
1547
1548const Type* upgradeGEPInstIndices(const Type* PTy,
1549 std::vector<ValueInfo> *Indices,
1550 std::vector<Value*> &Result) {
1551 const Type *Ty = PTy;
1552 Result.clear();
1553 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1554 Value *Index = (*Indices)[i].V;
1555
1556 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1557 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1558 // struct indices to i32 struct indices with ZExt for compatibility.
1559 if (CI->getBitWidth() < 32)
1560 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1561 }
1562
1563
1564 if (isa<StructType>(Ty)) { // Only change struct indices
1565 if (!isa<Constant>(Index)) {
1566 error("Invalid non-constant structure index");
1567 return 0;
1568 }
1569 } else {
1570 // Make sure that unsigned SequentialType indices are zext'd to
1571 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1572 // all indices for SequentialType elements. We must retain the same
1573 // semantic (zext) for unsigned types.
1574 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1575 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1576 if (isa<Constant>(Index))
1577 Index = ConstantExpr::getCast(Instruction::ZExt,
1578 cast<Constant>(Index), Type::Int64Ty);
1579 else
1580 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1581 makeNameUnique("gep"), CurBB);
1582 }
1583 }
1584 }
1585 Result.push_back(Index);
David Greene393be882007-09-04 15:46:09 +00001586 Ty = GetElementPtrInst::getIndexedType(PTy, Result.begin(),
1587 Result.end(),true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588 if (!Ty)
1589 error("Index list invalid for constant getelementptr");
1590 }
1591 return Ty;
1592}
1593
1594unsigned upgradeCallingConv(unsigned CC) {
1595 switch (CC) {
1596 case OldCallingConv::C : return CallingConv::C;
1597 case OldCallingConv::CSRet : return CallingConv::C;
1598 case OldCallingConv::Fast : return CallingConv::Fast;
1599 case OldCallingConv::Cold : return CallingConv::Cold;
1600 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1601 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1602 default:
1603 return CC;
1604 }
1605}
1606
1607Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1608 bool debug, bool addAttrs)
1609{
1610 Upgradelineno = 1;
1611 CurFilename = infile;
1612 LexInput = &in;
1613 yydebug = debug;
1614 AddAttributes = addAttrs;
1615 ObsoleteVarArgs = false;
1616 NewVarArgs = false;
1617
1618 CurModule.CurrentModule = new Module(CurFilename);
1619
1620 // Check to make sure the parser succeeded
1621 if (yyparse()) {
1622 if (ParserResult)
1623 delete ParserResult;
1624 std::cerr << "llvm-upgrade: parse failed.\n";
1625 return 0;
1626 }
1627
1628 // Check to make sure that parsing produced a result
1629 if (!ParserResult) {
1630 std::cerr << "llvm-upgrade: no parse result.\n";
1631 return 0;
1632 }
1633
1634 // Reset ParserResult variable while saving its value for the result.
1635 Module *Result = ParserResult;
1636 ParserResult = 0;
1637
1638 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1639 {
1640 Function* F;
1641 if ((F = Result->getFunction("llvm.va_start"))
1642 && F->getFunctionType()->getNumParams() == 0)
1643 ObsoleteVarArgs = true;
1644 if((F = Result->getFunction("llvm.va_copy"))
1645 && F->getFunctionType()->getNumParams() == 1)
1646 ObsoleteVarArgs = true;
1647 }
1648
1649 if (ObsoleteVarArgs && NewVarArgs) {
1650 error("This file is corrupt: it uses both new and old style varargs");
1651 return 0;
1652 }
1653
1654 if(ObsoleteVarArgs) {
1655 if(Function* F = Result->getFunction("llvm.va_start")) {
1656 if (F->arg_size() != 0) {
1657 error("Obsolete va_start takes 0 argument");
1658 return 0;
1659 }
1660
1661 //foo = va_start()
1662 // ->
1663 //bar = alloca typeof(foo)
1664 //va_start(bar)
1665 //foo = load bar
1666
1667 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1668 const Type* ArgTy = F->getFunctionType()->getReturnType();
1669 const Type* ArgTyPtr = PointerType::get(ArgTy);
1670 Function* NF = cast<Function>(Result->getOrInsertFunction(
1671 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1672
1673 while (!F->use_empty()) {
1674 CallInst* CI = cast<CallInst>(F->use_back());
1675 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1676 new CallInst(NF, bar, "", CI);
1677 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1678 CI->replaceAllUsesWith(foo);
1679 CI->getParent()->getInstList().erase(CI);
1680 }
1681 Result->getFunctionList().erase(F);
1682 }
1683
1684 if(Function* F = Result->getFunction("llvm.va_end")) {
1685 if(F->arg_size() != 1) {
1686 error("Obsolete va_end takes 1 argument");
1687 return 0;
1688 }
1689
1690 //vaend foo
1691 // ->
1692 //bar = alloca 1 of typeof(foo)
1693 //vaend bar
1694 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1695 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1696 const Type* ArgTyPtr = PointerType::get(ArgTy);
1697 Function* NF = cast<Function>(Result->getOrInsertFunction(
1698 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1699
1700 while (!F->use_empty()) {
1701 CallInst* CI = cast<CallInst>(F->use_back());
1702 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1703 new StoreInst(CI->getOperand(1), bar, CI);
1704 new CallInst(NF, bar, "", CI);
1705 CI->getParent()->getInstList().erase(CI);
1706 }
1707 Result->getFunctionList().erase(F);
1708 }
1709
1710 if(Function* F = Result->getFunction("llvm.va_copy")) {
1711 if(F->arg_size() != 1) {
1712 error("Obsolete va_copy takes 1 argument");
1713 return 0;
1714 }
1715 //foo = vacopy(bar)
1716 // ->
1717 //a = alloca 1 of typeof(foo)
1718 //b = alloca 1 of typeof(foo)
1719 //store bar -> b
1720 //vacopy(a, b)
1721 //foo = load a
1722
1723 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1724 const Type* ArgTy = F->getFunctionType()->getReturnType();
1725 const Type* ArgTyPtr = PointerType::get(ArgTy);
1726 Function* NF = cast<Function>(Result->getOrInsertFunction(
1727 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1728
1729 while (!F->use_empty()) {
1730 CallInst* CI = cast<CallInst>(F->use_back());
David Greene6182b122007-08-07 16:57:55 +00001731 Value *Args[2] = {
1732 new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI),
1733 new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI)
1734 };
David Greeneb1c4a7b2007-08-01 03:43:44 +00001735 new StoreInst(CI->getOperand(1), Args[1], CI);
David Greene6182b122007-08-07 16:57:55 +00001736 new CallInst(NF, Args, Args + 2, "", CI);
David Greeneb1c4a7b2007-08-01 03:43:44 +00001737 Value* foo = new LoadInst(Args[0], "vacopy.fix.3", CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738 CI->replaceAllUsesWith(foo);
1739 CI->getParent()->getInstList().erase(CI);
1740 }
1741 Result->getFunctionList().erase(F);
1742 }
1743 }
1744
1745 return Result;
1746}
1747
1748} // end llvm namespace
1749
1750using namespace llvm;
1751
1752%}
1753
1754%union {
1755 llvm::Module *ModuleVal;
1756 llvm::Function *FunctionVal;
1757 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1758 llvm::BasicBlock *BasicBlockVal;
1759 llvm::TermInstInfo TermInstVal;
1760 llvm::InstrInfo InstVal;
1761 llvm::ConstInfo ConstVal;
1762 llvm::ValueInfo ValueVal;
1763 llvm::PATypeInfo TypeVal;
1764 llvm::TypeInfo PrimType;
1765 llvm::PHIListInfo PHIList;
1766 std::list<llvm::PATypeInfo> *TypeList;
1767 std::vector<llvm::ValueInfo> *ValueList;
1768 std::vector<llvm::ConstInfo> *ConstVector;
1769
1770
1771 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1772 // Represent the RHS of PHI node
1773 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1774
1775 llvm::GlobalValue::LinkageTypes Linkage;
1776 int64_t SInt64Val;
1777 uint64_t UInt64Val;
1778 int SIntVal;
1779 unsigned UIntVal;
Dale Johannesenb9de9f02007-09-06 18:13:44 +00001780 llvm::APFloat *FPVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781 bool BoolVal;
1782
1783 char *StrVal; // This memory is strdup'd!
1784 llvm::ValID ValIDVal; // strdup'd memory maybe!
1785
1786 llvm::BinaryOps BinaryOpVal;
1787 llvm::TermOps TermOpVal;
1788 llvm::MemoryOps MemOpVal;
1789 llvm::OtherOps OtherOpVal;
1790 llvm::CastOps CastOpVal;
1791 llvm::ICmpInst::Predicate IPred;
1792 llvm::FCmpInst::Predicate FPred;
1793 llvm::Module::Endianness Endianness;
1794}
1795
1796%type <ModuleVal> Module FunctionList
1797%type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1798%type <BasicBlockVal> BasicBlock InstructionList
1799%type <TermInstVal> BBTerminatorInst
1800%type <InstVal> Inst InstVal MemoryInst
1801%type <ConstVal> ConstVal ConstExpr
1802%type <ConstVector> ConstVector
1803%type <ArgList> ArgList ArgListH
1804%type <ArgVal> ArgVal
1805%type <PHIList> PHIList
1806%type <ValueList> ValueRefList ValueRefListE // For call param lists
1807%type <ValueList> IndexList // For GEP derived indices
1808%type <TypeList> TypeListI ArgTypeListI
1809%type <JumpTable> JumpTable
1810%type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1811%type <BoolVal> OptVolatile // 'volatile' or not
1812%type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1813%type <BoolVal> OptSideEffect // 'sideeffect' or not.
1814%type <Linkage> OptLinkage FnDeclareLinkage
1815%type <Endianness> BigOrLittle
1816
1817// ValueRef - Unresolved reference to a definition or BB
1818%type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1819%type <ValueVal> ResolvedVal // <type> <valref> pair
1820
1821// Tokens and types for handling constant integer values
1822//
1823// ESINT64VAL - A negative number within long long range
1824%token <SInt64Val> ESINT64VAL
1825
1826// EUINT64VAL - A positive number within uns. long long range
1827%token <UInt64Val> EUINT64VAL
1828%type <SInt64Val> EINT64VAL
1829
1830%token <SIntVal> SINTVAL // Signed 32 bit ints...
1831%token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1832%type <SIntVal> INTVAL
1833%token <FPVal> FPVAL // Float or Double constant
1834
1835// Built in types...
1836%type <TypeVal> Types TypesV UpRTypes UpRTypesV
1837%type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1838%token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1839%token <PrimType> FLOAT DOUBLE TYPE LABEL
1840
1841%token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1842%type <StrVal> Name OptName OptAssign
1843%type <UIntVal> OptAlign OptCAlign
1844%type <StrVal> OptSection SectionString
1845
1846%token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1847%token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1848%token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1849%token DLLIMPORT DLLEXPORT EXTERN_WEAK
1850%token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1851%token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1852%token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1853%token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1854%token DATALAYOUT
1855%type <UIntVal> OptCallingConv
1856
1857// Basic Block Terminating Operators
1858%token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1859%token UNWIND EXCEPT
1860
1861// Binary Operators
1862%type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1863%type <BinaryOpVal> ShiftOps
1864%token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1865%token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1866%token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1867%token <OtherOpVal> ICMP FCMP
1868
1869// Memory Instructions
1870%token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1871
1872// Other Operators
1873%token <OtherOpVal> PHI_TOK SELECT VAARG
1874%token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1875%token VAARG_old VANEXT_old //OBSOLETE
1876
1877// Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1878%type <IPred> IPredicates
1879%type <FPred> FPredicates
1880%token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1881%token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1882
1883%token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1884%token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1885%type <CastOpVal> CastOps
1886
1887%start Module
1888
1889%%
1890
1891// Handle constant integer size restriction and conversion...
1892//
1893INTVAL
1894 : SINTVAL
1895 | UINTVAL {
1896 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1897 error("Value too large for type");
1898 $$ = (int32_t)$1;
1899 }
1900 ;
1901
1902EINT64VAL
1903 : ESINT64VAL // These have same type and can't cause problems...
1904 | EUINT64VAL {
1905 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1906 error("Value too large for type");
1907 $$ = (int64_t)$1;
1908 };
1909
1910// Operations that are notably excluded from this list include:
1911// RET, BR, & SWITCH because they end basic blocks and are treated specially.
1912//
1913ArithmeticOps
1914 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1915 ;
1916
1917LogicalOps
1918 : AND | OR | XOR
1919 ;
1920
1921SetCondOps
1922 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1923 ;
1924
1925IPredicates
1926 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1927 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1928 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1929 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1930 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1931 ;
1932
1933FPredicates
1934 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1935 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1936 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1937 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1938 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1939 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1940 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1941 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1942 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1943 ;
1944ShiftOps
1945 : SHL | SHR | ASHR | LSHR
1946 ;
1947
1948CastOps
1949 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1950 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1951 ;
1952
1953// These are some types that allow classification if we only want a particular
1954// thing... for example, only a signed, unsigned, or integral type.
1955SIntType
1956 : LONG | INT | SHORT | SBYTE
1957 ;
1958
1959UIntType
1960 : ULONG | UINT | USHORT | UBYTE
1961 ;
1962
1963IntType
1964 : SIntType | UIntType
1965 ;
1966
1967FPType
1968 : FLOAT | DOUBLE
1969 ;
1970
1971// OptAssign - Value producing statements have an optional assignment component
1972OptAssign
1973 : Name '=' {
1974 $$ = $1;
1975 }
1976 | /*empty*/ {
1977 $$ = 0;
1978 };
1979
1980OptLinkage
1981 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1982 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1983 | WEAK { $$ = GlobalValue::WeakLinkage; }
1984 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1985 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1986 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1987 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1988 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1989 ;
1990
1991OptCallingConv
1992 : /*empty*/ { $$ = lastCallingConv = OldCallingConv::C; }
1993 | CCC_TOK { $$ = lastCallingConv = OldCallingConv::C; }
1994 | CSRETCC_TOK { $$ = lastCallingConv = OldCallingConv::CSRet; }
1995 | FASTCC_TOK { $$ = lastCallingConv = OldCallingConv::Fast; }
1996 | COLDCC_TOK { $$ = lastCallingConv = OldCallingConv::Cold; }
1997 | X86_STDCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_StdCall; }
1998 | X86_FASTCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_FastCall; }
1999 | CC_TOK EUINT64VAL {
2000 if ((unsigned)$2 != $2)
2001 error("Calling conv too large");
2002 $$ = lastCallingConv = $2;
2003 }
2004 ;
2005
2006// OptAlign/OptCAlign - An optional alignment, and an optional alignment with
2007// a comma before it.
2008OptAlign
2009 : /*empty*/ { $$ = 0; }
2010 | ALIGN EUINT64VAL {
2011 $$ = $2;
2012 if ($$ != 0 && !isPowerOf2_32($$))
2013 error("Alignment must be a power of two");
2014 }
2015 ;
2016
2017OptCAlign
2018 : /*empty*/ { $$ = 0; }
2019 | ',' ALIGN EUINT64VAL {
2020 $$ = $3;
2021 if ($$ != 0 && !isPowerOf2_32($$))
2022 error("Alignment must be a power of two");
2023 }
2024 ;
2025
2026SectionString
2027 : SECTION STRINGCONSTANT {
2028 for (unsigned i = 0, e = strlen($2); i != e; ++i)
2029 if ($2[i] == '"' || $2[i] == '\\')
2030 error("Invalid character in section name");
2031 $$ = $2;
2032 }
2033 ;
2034
2035OptSection
2036 : /*empty*/ { $$ = 0; }
2037 | SectionString { $$ = $1; }
2038 ;
2039
2040// GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
2041// is set to be the global we are processing.
2042//
2043GlobalVarAttributes
2044 : /* empty */ {}
2045 | ',' GlobalVarAttribute GlobalVarAttributes {}
2046 ;
2047
2048GlobalVarAttribute
2049 : SectionString {
2050 CurGV->setSection($1);
2051 free($1);
2052 }
2053 | ALIGN EUINT64VAL {
2054 if ($2 != 0 && !isPowerOf2_32($2))
2055 error("Alignment must be a power of two");
2056 CurGV->setAlignment($2);
2057
2058 }
2059 ;
2060
2061//===----------------------------------------------------------------------===//
2062// Types includes all predefined types... except void, because it can only be
2063// used in specific contexts (function returning void for example). To have
2064// access to it, a user must explicitly use TypesV.
2065//
2066
2067// TypesV includes all of 'Types', but it also includes the void type.
2068TypesV
2069 : Types
2070 | VOID {
2071 $$.PAT = new PATypeHolder($1.T);
2072 $$.S.makeSignless();
2073 }
2074 ;
2075
2076UpRTypesV
2077 : UpRTypes
2078 | VOID {
2079 $$.PAT = new PATypeHolder($1.T);
2080 $$.S.makeSignless();
2081 }
2082 ;
2083
2084Types
2085 : UpRTypes {
2086 if (!UpRefs.empty())
2087 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
2088 $$ = $1;
2089 }
2090 ;
2091
2092PrimType
2093 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
2094 | LONG | ULONG | FLOAT | DOUBLE | LABEL
2095 ;
2096
2097// Derived types are added later...
2098UpRTypes
2099 : PrimType {
2100 $$.PAT = new PATypeHolder($1.T);
2101 $$.S.copy($1.S);
2102 }
2103 | OPAQUE {
2104 $$.PAT = new PATypeHolder(OpaqueType::get());
2105 $$.S.makeSignless();
2106 }
2107 | SymbolicValueRef { // Named types are also simple types...
2108 $$.S.copy(getTypeSign($1));
2109 const Type* tmp = getType($1);
2110 $$.PAT = new PATypeHolder(tmp);
2111 }
2112 | '\\' EUINT64VAL { // Type UpReference
2113 if ($2 > (uint64_t)~0U)
2114 error("Value out of range");
2115 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
2116 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
2117 $$.PAT = new PATypeHolder(OT);
2118 $$.S.makeSignless();
2119 UR_OUT("New Upreference!\n");
2120 }
2121 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
2122 $$.S.makeComposite($1.S);
2123 std::vector<const Type*> Params;
2124 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2125 E = $3->end(); I != E; ++I) {
2126 Params.push_back(I->PAT->get());
2127 $$.S.add(I->S);
2128 }
2129 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
2130 if (isVarArg) Params.pop_back();
2131
2132 ParamAttrsList *PAL = 0;
2133 if (lastCallingConv == OldCallingConv::CSRet) {
2134 ParamAttrsVector Attrs;
2135 ParamAttrsWithIndex PAWI;
2136 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
2137 Attrs.push_back(PAWI);
2138 PAL = ParamAttrsList::get(Attrs);
2139 }
2140
2141 const FunctionType *FTy =
2142 FunctionType::get($1.PAT->get(), Params, isVarArg, PAL);
2143
2144 $$.PAT = new PATypeHolder( HandleUpRefs(FTy, $$.S) );
2145 delete $1.PAT; // Delete the return type handle
2146 delete $3; // Delete the argument list
2147 }
2148 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
2149 $$.S.makeComposite($4.S);
2150 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
2151 (unsigned)$2), $$.S));
2152 delete $4.PAT;
2153 }
2154 | '<' EUINT64VAL 'x' UpRTypes '>' { // Vector type?
2155 const llvm::Type* ElemTy = $4.PAT->get();
2156 if ((unsigned)$2 != $2)
2157 error("Unsigned result not equal to signed result");
2158 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
2159 error("Elements of a VectorType must be integer or floating point");
2160 if (!isPowerOf2_32($2))
2161 error("VectorType length should be a power of 2");
2162 $$.S.makeComposite($4.S);
2163 $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy,
2164 (unsigned)$2), $$.S));
2165 delete $4.PAT;
2166 }
2167 | '{' TypeListI '}' { // Structure type?
2168 std::vector<const Type*> Elements;
2169 $$.S.makeComposite();
2170 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
2171 E = $2->end(); I != E; ++I) {
2172 Elements.push_back(I->PAT->get());
2173 $$.S.add(I->S);
2174 }
2175 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements), $$.S));
2176 delete $2;
2177 }
2178 | '{' '}' { // Empty structure type?
2179 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
2180 $$.S.makeComposite();
2181 }
2182 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
2183 $$.S.makeComposite();
2184 std::vector<const Type*> Elements;
2185 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2186 E = $3->end(); I != E; ++I) {
2187 Elements.push_back(I->PAT->get());
2188 $$.S.add(I->S);
2189 delete I->PAT;
2190 }
2191 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true),
2192 $$.S));
2193 delete $3;
2194 }
2195 | '<' '{' '}' '>' { // Empty packed structure type?
2196 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
2197 $$.S.makeComposite();
2198 }
2199 | UpRTypes '*' { // Pointer type?
2200 if ($1.PAT->get() == Type::LabelTy)
2201 error("Cannot form a pointer to a basic block");
2202 $$.S.makeComposite($1.S);
2203 $$.PAT = new PATypeHolder(HandleUpRefs(PointerType::get($1.PAT->get()),
2204 $$.S));
2205 delete $1.PAT;
2206 }
2207 ;
2208
2209// TypeList - Used for struct declarations and as a basis for function type
2210// declaration type lists
2211//
2212TypeListI
2213 : UpRTypes {
2214 $$ = new std::list<PATypeInfo>();
2215 $$->push_back($1);
2216 }
2217 | TypeListI ',' UpRTypes {
2218 ($$=$1)->push_back($3);
2219 }
2220 ;
2221
2222// ArgTypeList - List of types for a function type declaration...
2223ArgTypeListI
2224 : TypeListI
2225 | TypeListI ',' DOTDOTDOT {
2226 PATypeInfo VoidTI;
2227 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2228 VoidTI.S.makeSignless();
2229 ($$=$1)->push_back(VoidTI);
2230 }
2231 | DOTDOTDOT {
2232 $$ = new std::list<PATypeInfo>();
2233 PATypeInfo VoidTI;
2234 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2235 VoidTI.S.makeSignless();
2236 $$->push_back(VoidTI);
2237 }
2238 | /*empty*/ {
2239 $$ = new std::list<PATypeInfo>();
2240 }
2241 ;
2242
2243// ConstVal - The various declarations that go into the constant pool. This
2244// production is used ONLY to represent constants that show up AFTER a 'const',
2245// 'constant' or 'global' token at global scope. Constants that can be inlined
2246// into other expressions (such as integers and constexprs) are handled by the
2247// ResolvedVal, ValueRef and ConstValueRef productions.
2248//
2249ConstVal
2250 : Types '[' ConstVector ']' { // Nonempty unsized arr
2251 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2252 if (ATy == 0)
2253 error("Cannot make array constant with type: '" +
2254 $1.PAT->get()->getDescription() + "'");
2255 const Type *ETy = ATy->getElementType();
2256 int NumElements = ATy->getNumElements();
2257
2258 // Verify that we have the correct size...
2259 if (NumElements != -1 && NumElements != (int)$3->size())
2260 error("Type mismatch: constant sized array initialized with " +
2261 utostr($3->size()) + " arguments, but has size of " +
2262 itostr(NumElements) + "");
2263
2264 // Verify all elements are correct type!
2265 std::vector<Constant*> Elems;
2266 for (unsigned i = 0; i < $3->size(); i++) {
2267 Constant *C = (*$3)[i].C;
2268 const Type* ValTy = C->getType();
2269 if (ETy != ValTy)
2270 error("Element #" + utostr(i) + " is not of type '" +
2271 ETy->getDescription() +"' as required!\nIt is of type '"+
2272 ValTy->getDescription() + "'");
2273 Elems.push_back(C);
2274 }
2275 $$.C = ConstantArray::get(ATy, Elems);
2276 $$.S.copy($1.S);
2277 delete $1.PAT;
2278 delete $3;
2279 }
2280 | Types '[' ']' {
2281 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2282 if (ATy == 0)
2283 error("Cannot make array constant with type: '" +
2284 $1.PAT->get()->getDescription() + "'");
2285 int NumElements = ATy->getNumElements();
2286 if (NumElements != -1 && NumElements != 0)
2287 error("Type mismatch: constant sized array initialized with 0"
2288 " arguments, but has size of " + itostr(NumElements) +"");
2289 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
2290 $$.S.copy($1.S);
2291 delete $1.PAT;
2292 }
2293 | Types 'c' STRINGCONSTANT {
2294 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2295 if (ATy == 0)
2296 error("Cannot make array constant with type: '" +
2297 $1.PAT->get()->getDescription() + "'");
2298 int NumElements = ATy->getNumElements();
2299 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2300 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2301 error("String arrays require type i8, not '" + ETy->getDescription() +
2302 "'");
2303 char *EndStr = UnEscapeLexed($3, true);
2304 if (NumElements != -1 && NumElements != (EndStr-$3))
2305 error("Can't build string constant of size " +
2306 itostr((int)(EndStr-$3)) + " when array has size " +
2307 itostr(NumElements) + "");
2308 std::vector<Constant*> Vals;
2309 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2310 Vals.push_back(ConstantInt::get(ETy, *C));
2311 free($3);
2312 $$.C = ConstantArray::get(ATy, Vals);
2313 $$.S.copy($1.S);
2314 delete $1.PAT;
2315 }
2316 | Types '<' ConstVector '>' { // Nonempty unsized arr
2317 const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2318 if (PTy == 0)
2319 error("Cannot make packed constant with type: '" +
2320 $1.PAT->get()->getDescription() + "'");
2321 const Type *ETy = PTy->getElementType();
2322 int NumElements = PTy->getNumElements();
2323 // Verify that we have the correct size...
2324 if (NumElements != -1 && NumElements != (int)$3->size())
2325 error("Type mismatch: constant sized packed initialized with " +
2326 utostr($3->size()) + " arguments, but has size of " +
2327 itostr(NumElements) + "");
2328 // Verify all elements are correct type!
2329 std::vector<Constant*> Elems;
2330 for (unsigned i = 0; i < $3->size(); i++) {
2331 Constant *C = (*$3)[i].C;
2332 const Type* ValTy = C->getType();
2333 if (ETy != ValTy)
2334 error("Element #" + utostr(i) + " is not of type '" +
2335 ETy->getDescription() +"' as required!\nIt is of type '"+
2336 ValTy->getDescription() + "'");
2337 Elems.push_back(C);
2338 }
2339 $$.C = ConstantVector::get(PTy, Elems);
2340 $$.S.copy($1.S);
2341 delete $1.PAT;
2342 delete $3;
2343 }
2344 | Types '{' ConstVector '}' {
2345 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2346 if (STy == 0)
2347 error("Cannot make struct constant with type: '" +
2348 $1.PAT->get()->getDescription() + "'");
2349 if ($3->size() != STy->getNumContainedTypes())
2350 error("Illegal number of initializers for structure type");
2351
2352 // Check to ensure that constants are compatible with the type initializer!
2353 std::vector<Constant*> Fields;
2354 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2355 Constant *C = (*$3)[i].C;
2356 if (C->getType() != STy->getElementType(i))
2357 error("Expected type '" + STy->getElementType(i)->getDescription() +
2358 "' for element #" + utostr(i) + " of structure initializer");
2359 Fields.push_back(C);
2360 }
2361 $$.C = ConstantStruct::get(STy, Fields);
2362 $$.S.copy($1.S);
2363 delete $1.PAT;
2364 delete $3;
2365 }
2366 | Types '{' '}' {
2367 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2368 if (STy == 0)
2369 error("Cannot make struct constant with type: '" +
2370 $1.PAT->get()->getDescription() + "'");
2371 if (STy->getNumContainedTypes() != 0)
2372 error("Illegal number of initializers for structure type");
2373 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2374 $$.S.copy($1.S);
2375 delete $1.PAT;
2376 }
2377 | Types '<' '{' ConstVector '}' '>' {
2378 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2379 if (STy == 0)
2380 error("Cannot make packed struct constant with type: '" +
2381 $1.PAT->get()->getDescription() + "'");
2382 if ($4->size() != STy->getNumContainedTypes())
2383 error("Illegal number of initializers for packed structure type");
2384
2385 // Check to ensure that constants are compatible with the type initializer!
2386 std::vector<Constant*> Fields;
2387 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2388 Constant *C = (*$4)[i].C;
2389 if (C->getType() != STy->getElementType(i))
2390 error("Expected type '" + STy->getElementType(i)->getDescription() +
2391 "' for element #" + utostr(i) + " of packed struct initializer");
2392 Fields.push_back(C);
2393 }
2394 $$.C = ConstantStruct::get(STy, Fields);
2395 $$.S.copy($1.S);
2396 delete $1.PAT;
2397 delete $4;
2398 }
2399 | Types '<' '{' '}' '>' {
2400 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2401 if (STy == 0)
2402 error("Cannot make packed struct constant with type: '" +
2403 $1.PAT->get()->getDescription() + "'");
2404 if (STy->getNumContainedTypes() != 0)
2405 error("Illegal number of initializers for packed structure type");
2406 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2407 $$.S.copy($1.S);
2408 delete $1.PAT;
2409 }
2410 | Types NULL_TOK {
2411 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2412 if (PTy == 0)
2413 error("Cannot make null pointer constant with type: '" +
2414 $1.PAT->get()->getDescription() + "'");
2415 $$.C = ConstantPointerNull::get(PTy);
2416 $$.S.copy($1.S);
2417 delete $1.PAT;
2418 }
2419 | Types UNDEF {
2420 $$.C = UndefValue::get($1.PAT->get());
2421 $$.S.copy($1.S);
2422 delete $1.PAT;
2423 }
2424 | Types SymbolicValueRef {
2425 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2426 if (Ty == 0)
2427 error("Global const reference must be a pointer type, not" +
2428 $1.PAT->get()->getDescription());
2429
2430 // ConstExprs can exist in the body of a function, thus creating
2431 // GlobalValues whenever they refer to a variable. Because we are in
2432 // the context of a function, getExistingValue will search the functions
2433 // symbol table instead of the module symbol table for the global symbol,
2434 // which throws things all off. To get around this, we just tell
2435 // getExistingValue that we are at global scope here.
2436 //
2437 Function *SavedCurFn = CurFun.CurrentFunction;
2438 CurFun.CurrentFunction = 0;
2439 $2.S.copy($1.S);
2440 Value *V = getExistingValue(Ty, $2);
2441 CurFun.CurrentFunction = SavedCurFn;
2442
2443 // If this is an initializer for a constant pointer, which is referencing a
2444 // (currently) undefined variable, create a stub now that shall be replaced
2445 // in the future with the right type of variable.
2446 //
2447 if (V == 0) {
2448 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2449 const PointerType *PT = cast<PointerType>(Ty);
2450
2451 // First check to see if the forward references value is already created!
2452 PerModuleInfo::GlobalRefsType::iterator I =
2453 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2454
2455 if (I != CurModule.GlobalRefs.end()) {
2456 V = I->second; // Placeholder already exists, use it...
2457 $2.destroy();
2458 } else {
2459 std::string Name;
2460 if ($2.Type == ValID::NameVal) Name = $2.Name;
2461
2462 // Create the forward referenced global.
2463 GlobalValue *GV;
2464 if (const FunctionType *FTy =
2465 dyn_cast<FunctionType>(PT->getElementType())) {
2466 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2467 CurModule.CurrentModule);
2468 } else {
2469 GV = new GlobalVariable(PT->getElementType(), false,
2470 GlobalValue::ExternalLinkage, 0,
2471 Name, CurModule.CurrentModule);
2472 }
2473
2474 // Keep track of the fact that we have a forward ref to recycle it
2475 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2476 V = GV;
2477 }
2478 }
2479 $$.C = cast<GlobalValue>(V);
2480 $$.S.copy($1.S);
2481 delete $1.PAT; // Free the type handle
2482 }
2483 | Types ConstExpr {
2484 if ($1.PAT->get() != $2.C->getType())
2485 error("Mismatched types for constant expression");
2486 $$ = $2;
2487 $$.S.copy($1.S);
2488 delete $1.PAT;
2489 }
2490 | Types ZEROINITIALIZER {
2491 const Type *Ty = $1.PAT->get();
2492 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2493 error("Cannot create a null initialized value of this type");
2494 $$.C = Constant::getNullValue(Ty);
2495 $$.S.copy($1.S);
2496 delete $1.PAT;
2497 }
2498 | SIntType EINT64VAL { // integral constants
2499 const Type *Ty = $1.T;
2500 if (!ConstantInt::isValueValidForType(Ty, $2))
2501 error("Constant value doesn't fit in type");
2502 $$.C = ConstantInt::get(Ty, $2);
2503 $$.S.makeSigned();
2504 }
2505 | UIntType EUINT64VAL { // integral constants
2506 const Type *Ty = $1.T;
2507 if (!ConstantInt::isValueValidForType(Ty, $2))
2508 error("Constant value doesn't fit in type");
2509 $$.C = ConstantInt::get(Ty, $2);
2510 $$.S.makeUnsigned();
2511 }
2512 | BOOL TRUETOK { // Boolean constants
2513 $$.C = ConstantInt::get(Type::Int1Ty, true);
2514 $$.S.makeUnsigned();
2515 }
2516 | BOOL FALSETOK { // Boolean constants
2517 $$.C = ConstantInt::get(Type::Int1Ty, false);
2518 $$.S.makeUnsigned();
2519 }
2520 | FPType FPVAL { // Float & Double constants
Dale Johannesenb9de9f02007-09-06 18:13:44 +00002521 if (!ConstantFP::isValueValidForType($1.T, *$2))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002522 error("Floating point constant invalid for type");
Dale Johannesenb9de9f02007-09-06 18:13:44 +00002523 // Lexer has no type info, so builds all FP constants as double.
2524 // Fix this here.
2525 if ($1.T==Type::FloatTy)
2526 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
2527 $$.C = ConstantFP::get($1.T, *$2);
Dale Johannesen3afee192007-09-07 21:07:57 +00002528 delete $2;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529 $$.S.makeSignless();
2530 }
2531 ;
2532
2533ConstExpr
2534 : CastOps '(' ConstVal TO Types ')' {
2535 const Type* SrcTy = $3.C->getType();
2536 const Type* DstTy = $5.PAT->get();
2537 Signedness SrcSign($3.S);
2538 Signedness DstSign($5.S);
2539 if (!SrcTy->isFirstClassType())
2540 error("cast constant expression from a non-primitive type: '" +
2541 SrcTy->getDescription() + "'");
2542 if (!DstTy->isFirstClassType())
2543 error("cast constant expression to a non-primitive type: '" +
2544 DstTy->getDescription() + "'");
2545 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2546 $$.S.copy(DstSign);
2547 delete $5.PAT;
2548 }
2549 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2550 const Type *Ty = $3.C->getType();
2551 if (!isa<PointerType>(Ty))
2552 error("GetElementPtr requires a pointer operand");
2553
2554 std::vector<Constant*> CIndices;
2555 upgradeGEPCEIndices($3.C->getType(), $4, CIndices);
2556
2557 delete $4;
2558 $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2559 $$.S.copy(getElementSign($3, CIndices));
2560 }
2561 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2562 if (!$3.C->getType()->isInteger() ||
2563 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2564 error("Select condition must be bool type");
2565 if ($5.C->getType() != $7.C->getType())
2566 error("Select operand types must match");
2567 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2568 $$.S.copy($5.S);
2569 }
2570 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2571 const Type *Ty = $3.C->getType();
2572 if (Ty != $5.C->getType())
2573 error("Binary operator types must match");
2574 // First, make sure we're dealing with the right opcode by upgrading from
2575 // obsolete versions.
2576 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2577
2578 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2579 // To retain backward compatibility with these early compilers, we emit a
2580 // cast to the appropriate integer type automatically if we are in the
2581 // broken case. See PR424 for more information.
2582 if (!isa<PointerType>(Ty)) {
2583 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2584 } else {
2585 const Type *IntPtrTy = 0;
2586 switch (CurModule.CurrentModule->getPointerSize()) {
2587 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2588 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2589 default: error("invalid pointer binary constant expr");
2590 }
2591 $$.C = ConstantExpr::get(Opcode,
2592 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2593 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2594 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2595 }
2596 $$.S.copy($3.S);
2597 }
2598 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2599 const Type* Ty = $3.C->getType();
2600 if (Ty != $5.C->getType())
2601 error("Logical operator types must match");
2602 if (!Ty->isInteger()) {
2603 if (!isa<VectorType>(Ty) ||
2604 !cast<VectorType>(Ty)->getElementType()->isInteger())
2605 error("Logical operator requires integer operands");
2606 }
2607 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2608 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2609 $$.S.copy($3.S);
2610 }
2611 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2612 const Type* Ty = $3.C->getType();
2613 if (Ty != $5.C->getType())
2614 error("setcc operand types must match");
2615 unsigned short pred;
2616 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2617 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2618 $$.S.makeUnsigned();
2619 }
2620 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2621 if ($4.C->getType() != $6.C->getType())
2622 error("icmp operand types must match");
2623 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2624 $$.S.makeUnsigned();
2625 }
2626 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2627 if ($4.C->getType() != $6.C->getType())
2628 error("fcmp operand types must match");
2629 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2630 $$.S.makeUnsigned();
2631 }
2632 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2633 if (!$5.C->getType()->isInteger() ||
2634 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2635 error("Shift count for shift constant must be unsigned byte");
2636 const Type* Ty = $3.C->getType();
2637 if (!$3.C->getType()->isInteger())
2638 error("Shift constant expression requires integer operand");
2639 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2640 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2641 $$.S.copy($3.S);
2642 }
2643 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2644 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2645 error("Invalid extractelement operands");
2646 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2647 $$.S.copy($3.S.get(0));
2648 }
2649 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2650 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2651 error("Invalid insertelement operands");
2652 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2653 $$.S.copy($3.S);
2654 }
2655 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2656 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2657 error("Invalid shufflevector operands");
2658 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2659 $$.S.copy($3.S);
2660 }
2661 ;
2662
2663
2664// ConstVector - A list of comma separated constants.
2665ConstVector
2666 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2667 | ConstVal {
2668 $$ = new std::vector<ConstInfo>();
2669 $$->push_back($1);
2670 }
2671 ;
2672
2673
2674// GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2675GlobalType
2676 : GLOBAL { $$ = false; }
2677 | CONSTANT { $$ = true; }
2678 ;
2679
2680
2681//===----------------------------------------------------------------------===//
2682// Rules to match Modules
2683//===----------------------------------------------------------------------===//
2684
2685// Module rule: Capture the result of parsing the whole file into a result
2686// variable...
2687//
2688Module
2689 : FunctionList {
2690 $$ = ParserResult = $1;
2691 CurModule.ModuleDone();
2692 }
2693 ;
2694
2695// FunctionList - A list of functions, preceeded by a constant pool.
2696//
2697FunctionList
2698 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2699 | FunctionList FunctionProto { $$ = $1; }
2700 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2701 | FunctionList IMPLEMENTATION { $$ = $1; }
2702 | ConstPool {
2703 $$ = CurModule.CurrentModule;
2704 // Emit an error if there are any unresolved types left.
2705 if (!CurModule.LateResolveTypes.empty()) {
2706 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2707 if (DID.Type == ValID::NameVal) {
2708 error("Reference to an undefined type: '"+DID.getName() + "'");
2709 } else {
2710 error("Reference to an undefined type: #" + itostr(DID.Num));
2711 }
2712 }
2713 }
2714 ;
2715
2716// ConstPool - Constants with optional names assigned to them.
2717ConstPool
2718 : ConstPool OptAssign TYPE TypesV {
2719 // Eagerly resolve types. This is not an optimization, this is a
2720 // requirement that is due to the fact that we could have this:
2721 //
2722 // %list = type { %list * }
2723 // %list = type { %list * } ; repeated type decl
2724 //
2725 // If types are not resolved eagerly, then the two types will not be
2726 // determined to be the same type!
2727 //
2728 ResolveTypeTo($2, $4.PAT->get(), $4.S);
2729
2730 if (!setTypeName($4, $2) && !$2) {
2731 // If this is a numbered type that is not a redefinition, add it to the
2732 // slot table.
2733 CurModule.Types.push_back($4.PAT->get());
2734 CurModule.TypeSigns.push_back($4.S);
2735 }
2736 delete $4.PAT;
2737 }
2738 | ConstPool FunctionProto { // Function prototypes can be in const pool
2739 }
2740 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2741 }
2742 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2743 if ($5.C == 0)
2744 error("Global value initializer is not a constant");
2745 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2746 } GlobalVarAttributes {
2747 CurGV = 0;
2748 }
2749 | ConstPool OptAssign EXTERNAL GlobalType Types {
2750 const Type *Ty = $5.PAT->get();
2751 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2752 $5.S);
2753 delete $5.PAT;
2754 } GlobalVarAttributes {
2755 CurGV = 0;
2756 }
2757 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2758 const Type *Ty = $5.PAT->get();
2759 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2760 $5.S);
2761 delete $5.PAT;
2762 } GlobalVarAttributes {
2763 CurGV = 0;
2764 }
2765 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2766 const Type *Ty = $5.PAT->get();
2767 CurGV =
2768 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0,
2769 $5.S);
2770 delete $5.PAT;
2771 } GlobalVarAttributes {
2772 CurGV = 0;
2773 }
2774 | ConstPool TARGET TargetDefinition {
2775 }
2776 | ConstPool DEPLIBS '=' LibrariesDefinition {
2777 }
2778 | /* empty: end of list */ {
2779 }
2780 ;
2781
2782AsmBlock
2783 : STRINGCONSTANT {
2784 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2785 char *EndStr = UnEscapeLexed($1, true);
2786 std::string NewAsm($1, EndStr);
2787 free($1);
2788
2789 if (AsmSoFar.empty())
2790 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2791 else
2792 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2793 }
2794 ;
2795
2796BigOrLittle
2797 : BIG { $$ = Module::BigEndian; }
2798 | LITTLE { $$ = Module::LittleEndian; }
2799 ;
2800
2801TargetDefinition
2802 : ENDIAN '=' BigOrLittle {
2803 CurModule.setEndianness($3);
2804 }
2805 | POINTERSIZE '=' EUINT64VAL {
2806 if ($3 == 32)
2807 CurModule.setPointerSize(Module::Pointer32);
2808 else if ($3 == 64)
2809 CurModule.setPointerSize(Module::Pointer64);
2810 else
2811 error("Invalid pointer size: '" + utostr($3) + "'");
2812 }
2813 | TRIPLE '=' STRINGCONSTANT {
2814 CurModule.CurrentModule->setTargetTriple($3);
2815 free($3);
2816 }
2817 | DATALAYOUT '=' STRINGCONSTANT {
2818 CurModule.CurrentModule->setDataLayout($3);
2819 free($3);
2820 }
2821 ;
2822
2823LibrariesDefinition
2824 : '[' LibList ']'
2825 ;
2826
2827LibList
2828 : LibList ',' STRINGCONSTANT {
2829 CurModule.CurrentModule->addLibrary($3);
2830 free($3);
2831 }
2832 | STRINGCONSTANT {
2833 CurModule.CurrentModule->addLibrary($1);
2834 free($1);
2835 }
2836 | /* empty: end of list */ { }
2837 ;
2838
2839//===----------------------------------------------------------------------===//
2840// Rules to match Function Headers
2841//===----------------------------------------------------------------------===//
2842
2843Name
2844 : VAR_ID | STRINGCONSTANT
2845 ;
2846
2847OptName
2848 : Name
2849 | /*empty*/ { $$ = 0; }
2850 ;
2851
2852ArgVal
2853 : Types OptName {
2854 if ($1.PAT->get() == Type::VoidTy)
2855 error("void typed arguments are invalid");
2856 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2857 }
2858 ;
2859
2860ArgListH
2861 : ArgListH ',' ArgVal {
2862 $$ = $1;
2863 $$->push_back(*$3);
2864 delete $3;
2865 }
2866 | ArgVal {
2867 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2868 $$->push_back(*$1);
2869 delete $1;
2870 }
2871 ;
2872
2873ArgList
2874 : ArgListH { $$ = $1; }
2875 | ArgListH ',' DOTDOTDOT {
2876 $$ = $1;
2877 PATypeInfo VoidTI;
2878 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2879 VoidTI.S.makeSignless();
2880 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2881 }
2882 | DOTDOTDOT {
2883 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2884 PATypeInfo VoidTI;
2885 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2886 VoidTI.S.makeSignless();
2887 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2888 }
2889 | /* empty */ { $$ = 0; }
2890 ;
2891
2892FunctionHeaderH
2893 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2894 UnEscapeLexed($3);
2895 std::string FunctionName($3);
2896 free($3); // Free strdup'd memory!
2897
2898 const Type* RetTy = $2.PAT->get();
2899
2900 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2901 error("LLVM functions cannot return aggregate types");
2902
2903 Signedness FTySign;
2904 FTySign.makeComposite($2.S);
2905 std::vector<const Type*> ParamTyList;
2906
2907 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2908 // i8*. We check here for those names and override the parameter list
2909 // types to ensure the prototype is correct.
2910 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2911 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2912 } else if (FunctionName == "llvm.va_copy") {
2913 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2914 ParamTyList.push_back(PointerType::get(Type::Int8Ty));
2915 } else if ($5) { // If there are arguments...
2916 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2917 I = $5->begin(), E = $5->end(); I != E; ++I) {
2918 const Type *Ty = I->first.PAT->get();
2919 ParamTyList.push_back(Ty);
2920 FTySign.add(I->first.S);
2921 }
2922 }
2923
2924 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2925 if (isVarArg)
2926 ParamTyList.pop_back();
2927
2928 // Convert the CSRet calling convention into the corresponding parameter
2929 // attribute.
2930 ParamAttrsList *PAL = 0;
2931 if ($1 == OldCallingConv::CSRet) {
2932 ParamAttrsVector Attrs;
2933 ParamAttrsWithIndex PAWI;
2934 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
2935 Attrs.push_back(PAWI);
2936 PAL = ParamAttrsList::get(Attrs);
2937 }
2938
2939 const FunctionType *FT =
2940 FunctionType::get(RetTy, ParamTyList, isVarArg, PAL);
2941 const PointerType *PFT = PointerType::get(FT);
2942 delete $2.PAT;
2943
2944 ValID ID;
2945 if (!FunctionName.empty()) {
2946 ID = ValID::create((char*)FunctionName.c_str());
2947 } else {
2948 ID = ValID::create((int)CurModule.Values[PFT].size());
2949 }
2950 ID.S.makeComposite(FTySign);
2951
2952 Function *Fn = 0;
2953 Module* M = CurModule.CurrentModule;
2954
2955 // See if this function was forward referenced. If so, recycle the object.
2956 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2957 // Move the function to the end of the list, from whereever it was
2958 // previously inserted.
2959 Fn = cast<Function>(FWRef);
2960 M->getFunctionList().remove(Fn);
2961 M->getFunctionList().push_back(Fn);
2962 } else if (!FunctionName.empty()) {
2963 GlobalValue *Conflict = M->getFunction(FunctionName);
2964 if (!Conflict)
2965 Conflict = M->getNamedGlobal(FunctionName);
2966 if (Conflict && PFT == Conflict->getType()) {
2967 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2968 // We have two function definitions that conflict, same type, same
2969 // name. We should really check to make sure that this is the result
2970 // of integer type planes collapsing and generate an error if it is
2971 // not, but we'll just rename on the assumption that it is. However,
2972 // let's do it intelligently and rename the internal linkage one
2973 // if there is one.
2974 std::string NewName(makeNameUnique(FunctionName));
2975 if (Conflict->hasInternalLinkage()) {
2976 Conflict->setName(NewName);
2977 RenameMapKey Key =
2978 makeRenameMapKey(FunctionName, Conflict->getType(), ID.S);
2979 CurModule.RenameMap[Key] = NewName;
2980 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2981 InsertValue(Fn, CurModule.Values);
2982 } else {
2983 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2984 InsertValue(Fn, CurModule.Values);
2985 RenameMapKey Key =
2986 makeRenameMapKey(FunctionName, PFT, ID.S);
2987 CurModule.RenameMap[Key] = NewName;
2988 }
2989 } else {
2990 // If they are not both definitions, then just use the function we
2991 // found since the types are the same.
2992 Fn = cast<Function>(Conflict);
2993
2994 // Make sure to strip off any argument names so we can't get
2995 // conflicts.
2996 if (Fn->isDeclaration())
2997 for (Function::arg_iterator AI = Fn->arg_begin(),
2998 AE = Fn->arg_end(); AI != AE; ++AI)
2999 AI->setName("");
3000 }
3001 } else if (Conflict) {
3002 // We have two globals with the same name and different types.
3003 // Previously, this was permitted because the symbol table had
3004 // "type planes" and names only needed to be distinct within a
3005 // type plane. After PR411 was fixed, this is no loner the case.
3006 // To resolve this we must rename one of the two.
3007 if (Conflict->hasInternalLinkage()) {
3008 // We can safely rename the Conflict.
3009 RenameMapKey Key =
3010 makeRenameMapKey(Conflict->getName(), Conflict->getType(),
3011 CurModule.NamedValueSigns[Conflict->getName()]);
3012 Conflict->setName(makeNameUnique(Conflict->getName()));
3013 CurModule.RenameMap[Key] = Conflict->getName();
3014 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
3015 InsertValue(Fn, CurModule.Values);
3016 } else {
3017 // We can't quietly rename either of these things, but we must
3018 // rename one of them. Only if the function's linkage is internal can
3019 // we forgo a warning message about the renamed function.
3020 std::string NewName = makeNameUnique(FunctionName);
3021 if (CurFun.Linkage != GlobalValue::InternalLinkage) {
3022 warning("Renaming function '" + FunctionName + "' as '" + NewName +
3023 "' may cause linkage errors");
3024 }
3025 // Elect to rename the thing we're now defining.
3026 Fn = new Function(FT, CurFun.Linkage, NewName, M);
3027 InsertValue(Fn, CurModule.Values);
3028 RenameMapKey Key = makeRenameMapKey(FunctionName, PFT, ID.S);
3029 CurModule.RenameMap[Key] = NewName;
3030 }
3031 } else {
3032 // There's no conflict, just define the function
3033 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
3034 InsertValue(Fn, CurModule.Values);
3035 }
3036 } else {
3037 // There's no conflict, just define the function
3038 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
3039 InsertValue(Fn, CurModule.Values);
3040 }
3041
3042
3043 CurFun.FunctionStart(Fn);
3044
3045 if (CurFun.isDeclare) {
3046 // If we have declaration, always overwrite linkage. This will allow us
3047 // to correctly handle cases, when pointer to function is passed as
3048 // argument to another function.
3049 Fn->setLinkage(CurFun.Linkage);
3050 }
3051 Fn->setCallingConv(upgradeCallingConv($1));
3052 Fn->setAlignment($8);
3053 if ($7) {
3054 Fn->setSection($7);
3055 free($7);
3056 }
3057
3058 // Add all of the arguments we parsed to the function...
3059 if ($5) { // Is null if empty...
3060 if (isVarArg) { // Nuke the last entry
3061 assert($5->back().first.PAT->get() == Type::VoidTy &&
3062 $5->back().second == 0 && "Not a varargs marker");
3063 delete $5->back().first.PAT;
3064 $5->pop_back(); // Delete the last entry
3065 }
3066 Function::arg_iterator ArgIt = Fn->arg_begin();
3067 Function::arg_iterator ArgEnd = Fn->arg_end();
3068 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
3069 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
3070 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
3071 delete I->first.PAT; // Delete the typeholder...
3072 ValueInfo VI; VI.V = ArgIt; VI.S.copy(I->first.S);
3073 setValueName(VI, I->second); // Insert arg into symtab...
3074 InsertValue(ArgIt);
3075 }
3076 delete $5; // We're now done with the argument list
3077 }
3078 lastCallingConv = OldCallingConv::C;
3079 }
3080 ;
3081
3082BEGIN
3083 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
3084 ;
3085
3086FunctionHeader
3087 : OptLinkage { CurFun.Linkage = $1; } FunctionHeaderH BEGIN {
3088 $$ = CurFun.CurrentFunction;
3089
3090 // Make sure that we keep track of the linkage type even if there was a
3091 // previous "declare".
3092 $$->setLinkage($1);
3093 }
3094 ;
3095
3096END
3097 : ENDTOK | '}' // Allow end of '}' to end a function
3098 ;
3099
3100Function
3101 : BasicBlockList END {
3102 $$ = $1;
3103 };
3104
3105FnDeclareLinkage
3106 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
3107 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
3108 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
3109 ;
3110
3111FunctionProto
3112 : DECLARE { CurFun.isDeclare = true; }
3113 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
3114 $$ = CurFun.CurrentFunction;
3115 CurFun.FunctionDone();
3116
3117 }
3118 ;
3119
3120//===----------------------------------------------------------------------===//
3121// Rules to match Basic Blocks
3122//===----------------------------------------------------------------------===//
3123
3124OptSideEffect
3125 : /* empty */ { $$ = false; }
3126 | SIDEEFFECT { $$ = true; }
3127 ;
3128
3129ConstValueRef
3130 // A reference to a direct constant
3131 : ESINT64VAL { $$ = ValID::create($1); }
3132 | EUINT64VAL { $$ = ValID::create($1); }
3133 | FPVAL { $$ = ValID::create($1); }
3134 | TRUETOK {
3135 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true));
3136 $$.S.makeUnsigned();
3137 }
3138 | FALSETOK {
3139 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false));
3140 $$.S.makeUnsigned();
3141 }
3142 | NULL_TOK { $$ = ValID::createNull(); }
3143 | UNDEF { $$ = ValID::createUndef(); }
3144 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
3145 | '<' ConstVector '>' { // Nonempty unsized packed vector
3146 const Type *ETy = (*$2)[0].C->getType();
3147 int NumElements = $2->size();
3148 VectorType* pt = VectorType::get(ETy, NumElements);
3149 $$.S.makeComposite((*$2)[0].S);
3150 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt, $$.S));
3151
3152 // Verify all elements are correct type!
3153 std::vector<Constant*> Elems;
3154 for (unsigned i = 0; i < $2->size(); i++) {
3155 Constant *C = (*$2)[i].C;
3156 const Type *CTy = C->getType();
3157 if (ETy != CTy)
3158 error("Element #" + utostr(i) + " is not of type '" +
3159 ETy->getDescription() +"' as required!\nIt is of type '" +
3160 CTy->getDescription() + "'");
3161 Elems.push_back(C);
3162 }
3163 $$ = ValID::create(ConstantVector::get(pt, Elems));
3164 delete PTy; delete $2;
3165 }
3166 | ConstExpr {
3167 $$ = ValID::create($1.C);
3168 $$.S.copy($1.S);
3169 }
3170 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
3171 char *End = UnEscapeLexed($3, true);
3172 std::string AsmStr = std::string($3, End);
3173 End = UnEscapeLexed($5, true);
3174 std::string Constraints = std::string($5, End);
3175 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
3176 free($3);
3177 free($5);
3178 }
3179 ;
3180
3181// SymbolicValueRef - Reference to one of two ways of symbolically refering to // another value.
3182//
3183SymbolicValueRef
3184 : INTVAL { $$ = ValID::create($1); $$.S.makeSignless(); }
3185 | Name { $$ = ValID::create($1); $$.S.makeSignless(); }
3186 ;
3187
3188// ValueRef - A reference to a definition... either constant or symbolic
3189ValueRef
3190 : SymbolicValueRef | ConstValueRef
3191 ;
3192
3193
3194// ResolvedVal - a <type> <value> pair. This is used only in cases where the
3195// type immediately preceeds the value reference, and allows complex constant
3196// pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
3197ResolvedVal
3198 : Types ValueRef {
3199 const Type *Ty = $1.PAT->get();
3200 $2.S.copy($1.S);
3201 $$.V = getVal(Ty, $2);
3202 $$.S.copy($1.S);
3203 delete $1.PAT;
3204 }
3205 ;
3206
3207BasicBlockList
3208 : BasicBlockList BasicBlock {
3209 $$ = $1;
3210 }
3211 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
3212 $$ = $1;
3213 };
3214
3215
3216// Basic blocks are terminated by branching instructions:
3217// br, br/cc, switch, ret
3218//
3219BasicBlock
3220 : InstructionList OptAssign BBTerminatorInst {
3221 ValueInfo VI; VI.V = $3.TI; VI.S.copy($3.S);
3222 setValueName(VI, $2);
3223 InsertValue($3.TI);
3224 $1->getInstList().push_back($3.TI);
3225 InsertValue($1);
3226 $$ = $1;
3227 }
3228 ;
3229
3230InstructionList
3231 : InstructionList Inst {
3232 if ($2.I)
3233 $1->getInstList().push_back($2.I);
3234 $$ = $1;
3235 }
3236 | /* empty */ {
3237 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++),true);
3238 // Make sure to move the basic block to the correct location in the
3239 // function, instead of leaving it inserted wherever it was first
3240 // referenced.
3241 Function::BasicBlockListType &BBL =
3242 CurFun.CurrentFunction->getBasicBlockList();
3243 BBL.splice(BBL.end(), BBL, $$);
3244 }
3245 | LABELSTR {
3246 $$ = CurBB = getBBVal(ValID::create($1), true);
3247 // Make sure to move the basic block to the correct location in the
3248 // function, instead of leaving it inserted wherever it was first
3249 // referenced.
3250 Function::BasicBlockListType &BBL =
3251 CurFun.CurrentFunction->getBasicBlockList();
3252 BBL.splice(BBL.end(), BBL, $$);
3253 }
3254 ;
3255
3256Unwind : UNWIND | EXCEPT;
3257
3258BBTerminatorInst
3259 : RET ResolvedVal { // Return with a result...
3260 $$.TI = new ReturnInst($2.V);
3261 $$.S.makeSignless();
3262 }
3263 | RET VOID { // Return with no result...
3264 $$.TI = new ReturnInst();
3265 $$.S.makeSignless();
3266 }
3267 | BR LABEL ValueRef { // Unconditional Branch...
3268 BasicBlock* tmpBB = getBBVal($3);
3269 $$.TI = new BranchInst(tmpBB);
3270 $$.S.makeSignless();
3271 } // Conditional Branch...
3272 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
3273 $6.S.makeSignless();
3274 $9.S.makeSignless();
3275 BasicBlock* tmpBBA = getBBVal($6);
3276 BasicBlock* tmpBBB = getBBVal($9);
3277 $3.S.makeUnsigned();
3278 Value* tmpVal = getVal(Type::Int1Ty, $3);
3279 $$.TI = new BranchInst(tmpBBA, tmpBBB, tmpVal);
3280 $$.S.makeSignless();
3281 }
3282 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
3283 $3.S.copy($2.S);
3284 Value* tmpVal = getVal($2.T, $3);
3285 $6.S.makeSignless();
3286 BasicBlock* tmpBB = getBBVal($6);
3287 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
3288 $$.TI = S;
3289 $$.S.makeSignless();
3290 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
3291 E = $8->end();
3292 for (; I != E; ++I) {
3293 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
3294 S->addCase(CI, I->second);
3295 else
3296 error("Switch case is constant, but not a simple integer");
3297 }
3298 delete $8;
3299 }
3300 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
3301 $3.S.copy($2.S);
3302 Value* tmpVal = getVal($2.T, $3);
3303 $6.S.makeSignless();
3304 BasicBlock* tmpBB = getBBVal($6);
3305 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
3306 $$.TI = S;
3307 $$.S.makeSignless();
3308 }
3309 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
3310 TO LABEL ValueRef Unwind LABEL ValueRef {
3311 const PointerType *PFTy;
3312 const FunctionType *Ty;
3313 Signedness FTySign;
3314
3315 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3316 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3317 // Pull out the types of all of the arguments...
3318 std::vector<const Type*> ParamTypes;
3319 FTySign.makeComposite($3.S);
3320 if ($6) {
3321 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3322 I != E; ++I) {
3323 ParamTypes.push_back((*I).V->getType());
3324 FTySign.add(I->S);
3325 }
3326 }
3327 ParamAttrsList *PAL = 0;
3328 if ($2 == OldCallingConv::CSRet) {
3329 ParamAttrsVector Attrs;
3330 ParamAttrsWithIndex PAWI;
3331 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
3332 Attrs.push_back(PAWI);
3333 PAL = ParamAttrsList::get(Attrs);
3334 }
3335 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3336 if (isVarArg) ParamTypes.pop_back();
3337 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg, PAL);
3338 PFTy = PointerType::get(Ty);
3339 $$.S.copy($3.S);
3340 } else {
3341 FTySign = $3.S;
3342 // Get the signedness of the result type. $3 is the pointer to the
3343 // function type so we get the 0th element to extract the function type,
3344 // and then the 0th element again to get the result type.
3345 $$.S.copy($3.S.get(0).get(0));
3346 }
3347
3348 $4.S.makeComposite(FTySign);
3349 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3350 BasicBlock *Normal = getBBVal($10);
3351 BasicBlock *Except = getBBVal($13);
3352
3353 // Create the call node...
3354 if (!$6) { // Has no arguments?
David Greene8278ef52007-08-27 19:04:21 +00003355 std::vector<Value*> Args;
3356 $$.TI = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357 } else { // Has arguments?
3358 // Loop through FunctionType's arguments and ensure they are specified
3359 // correctly!
3360 //
3361 FunctionType::param_iterator I = Ty->param_begin();
3362 FunctionType::param_iterator E = Ty->param_end();
3363 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3364
3365 std::vector<Value*> Args;
3366 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3367 if ((*ArgI).V->getType() != *I)
3368 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3369 (*I)->getDescription() + "'");
3370 Args.push_back((*ArgI).V);
3371 }
3372
3373 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3374 error("Invalid number of parameters detected");
3375
David Greene8278ef52007-08-27 19:04:21 +00003376 $$.TI = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 }
3378 cast<InvokeInst>($$.TI)->setCallingConv(upgradeCallingConv($2));
3379 delete $3.PAT;
3380 delete $6;
3381 lastCallingConv = OldCallingConv::C;
3382 }
3383 | Unwind {
3384 $$.TI = new UnwindInst();
3385 $$.S.makeSignless();
3386 }
3387 | UNREACHABLE {
3388 $$.TI = new UnreachableInst();
3389 $$.S.makeSignless();
3390 }
3391 ;
3392
3393JumpTable
3394 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3395 $$ = $1;
3396 $3.S.copy($2.S);
3397 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3398
3399 if (V == 0)
3400 error("May only switch on a constant pool value");
3401
3402 $6.S.makeSignless();
3403 BasicBlock* tmpBB = getBBVal($6);
3404 $$->push_back(std::make_pair(V, tmpBB));
3405 }
3406 | IntType ConstValueRef ',' LABEL ValueRef {
3407 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3408 $2.S.copy($1.S);
3409 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3410
3411 if (V == 0)
3412 error("May only switch on a constant pool value");
3413
3414 $5.S.makeSignless();
3415 BasicBlock* tmpBB = getBBVal($5);
3416 $$->push_back(std::make_pair(V, tmpBB));
3417 }
3418 ;
3419
3420Inst
3421 : OptAssign InstVal {
3422 bool omit = false;
3423 if ($1)
3424 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3425 if (BCI->getSrcTy() == BCI->getDestTy() &&
3426 BCI->getOperand(0)->getName() == $1)
3427 // This is a useless bit cast causing a name redefinition. It is
3428 // a bit cast from a type to the same type of an operand with the
3429 // same name as the name we would give this instruction. Since this
3430 // instruction results in no code generation, it is safe to omit
3431 // the instruction. This situation can occur because of collapsed
3432 // type planes. For example:
3433 // %X = add int %Y, %Z
3434 // %X = cast int %Y to uint
3435 // After upgrade, this looks like:
3436 // %X = add i32 %Y, %Z
3437 // %X = bitcast i32 to i32
3438 // The bitcast is clearly useless so we omit it.
3439 omit = true;
3440 if (omit) {
3441 $$.I = 0;
3442 $$.S.makeSignless();
3443 } else {
3444 ValueInfo VI; VI.V = $2.I; VI.S.copy($2.S);
3445 setValueName(VI, $1);
3446 InsertValue($2.I);
3447 $$ = $2;
3448 }
3449 };
3450
3451PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3452 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3453 $$.S.copy($1.S);
3454 $3.S.copy($1.S);
3455 Value* tmpVal = getVal($1.PAT->get(), $3);
3456 $5.S.makeSignless();
3457 BasicBlock* tmpBB = getBBVal($5);
3458 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3459 delete $1.PAT;
3460 }
3461 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3462 $$ = $1;
3463 $4.S.copy($1.S);
3464 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3465 $6.S.makeSignless();
3466 BasicBlock* tmpBB = getBBVal($6);
3467 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3468 }
3469 ;
3470
3471ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3472 $$ = new std::vector<ValueInfo>();
3473 $$->push_back($1);
3474 }
3475 | ValueRefList ',' ResolvedVal {
3476 $$ = $1;
3477 $1->push_back($3);
3478 };
3479
3480// ValueRefListE - Just like ValueRefList, except that it may also be empty!
3481ValueRefListE
3482 : ValueRefList
3483 | /*empty*/ { $$ = 0; }
3484 ;
3485
3486OptTailCall
3487 : TAIL CALL {
3488 $$ = true;
3489 }
3490 | CALL {
3491 $$ = false;
3492 }
3493 ;
3494
3495InstVal
3496 : ArithmeticOps Types ValueRef ',' ValueRef {
3497 $3.S.copy($2.S);
3498 $5.S.copy($2.S);
3499 const Type* Ty = $2.PAT->get();
3500 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3501 error("Arithmetic operator requires integer, FP, or packed operands");
3502 if (isa<VectorType>(Ty) &&
3503 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3504 error("Remainder not supported on vector types");
3505 // Upgrade the opcode from obsolete versions before we do anything with it.
3506 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3507 Value* val1 = getVal(Ty, $3);
3508 Value* val2 = getVal(Ty, $5);
3509 $$.I = BinaryOperator::create(Opcode, val1, val2);
3510 if ($$.I == 0)
3511 error("binary operator returned null");
3512 $$.S.copy($2.S);
3513 delete $2.PAT;
3514 }
3515 | LogicalOps Types ValueRef ',' ValueRef {
3516 $3.S.copy($2.S);
3517 $5.S.copy($2.S);
3518 const Type *Ty = $2.PAT->get();
3519 if (!Ty->isInteger()) {
3520 if (!isa<VectorType>(Ty) ||
3521 !cast<VectorType>(Ty)->getElementType()->isInteger())
3522 error("Logical operator requires integral operands");
3523 }
3524 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3525 Value* tmpVal1 = getVal(Ty, $3);
3526 Value* tmpVal2 = getVal(Ty, $5);
3527 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3528 if ($$.I == 0)
3529 error("binary operator returned null");
3530 $$.S.copy($2.S);
3531 delete $2.PAT;
3532 }
3533 | SetCondOps Types ValueRef ',' ValueRef {
3534 $3.S.copy($2.S);
3535 $5.S.copy($2.S);
3536 const Type* Ty = $2.PAT->get();
3537 if(isa<VectorType>(Ty))
3538 error("VectorTypes currently not supported in setcc instructions");
3539 unsigned short pred;
3540 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3541 Value* tmpVal1 = getVal(Ty, $3);
3542 Value* tmpVal2 = getVal(Ty, $5);
3543 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3544 if ($$.I == 0)
3545 error("binary operator returned null");
3546 $$.S.makeUnsigned();
3547 delete $2.PAT;
3548 }
3549 | ICMP IPredicates Types ValueRef ',' ValueRef {
3550 $4.S.copy($3.S);
3551 $6.S.copy($3.S);
3552 const Type *Ty = $3.PAT->get();
3553 if (isa<VectorType>(Ty))
3554 error("VectorTypes currently not supported in icmp instructions");
3555 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3556 error("icmp requires integer or pointer typed operands");
3557 Value* tmpVal1 = getVal(Ty, $4);
3558 Value* tmpVal2 = getVal(Ty, $6);
3559 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3560 $$.S.makeUnsigned();
3561 delete $3.PAT;
3562 }
3563 | FCMP FPredicates Types ValueRef ',' ValueRef {
3564 $4.S.copy($3.S);
3565 $6.S.copy($3.S);
3566 const Type *Ty = $3.PAT->get();
3567 if (isa<VectorType>(Ty))
3568 error("VectorTypes currently not supported in fcmp instructions");
3569 else if (!Ty->isFloatingPoint())
3570 error("fcmp instruction requires floating point operands");
3571 Value* tmpVal1 = getVal(Ty, $4);
3572 Value* tmpVal2 = getVal(Ty, $6);
3573 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3574 $$.S.makeUnsigned();
3575 delete $3.PAT;
3576 }
3577 | NOT ResolvedVal {
3578 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3579 const Type *Ty = $2.V->getType();
3580 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3581 if (Ones == 0)
3582 error("Expected integral type for not instruction");
3583 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3584 if ($$.I == 0)
3585 error("Could not create a xor instruction");
3586 $$.S.copy($2.S);
3587 }
3588 | ShiftOps ResolvedVal ',' ResolvedVal {
3589 if (!$4.V->getType()->isInteger() ||
3590 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3591 error("Shift amount must be int8");
3592 const Type* Ty = $2.V->getType();
3593 if (!Ty->isInteger())
3594 error("Shift constant expression requires integer operand");
3595 Value* ShiftAmt = 0;
3596 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3597 if (Constant *C = dyn_cast<Constant>($4.V))
3598 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3599 else
3600 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3601 else
3602 ShiftAmt = $4.V;
3603 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3604 $$.S.copy($2.S);
3605 }
3606 | CastOps ResolvedVal TO Types {
3607 const Type *DstTy = $4.PAT->get();
3608 if (!DstTy->isFirstClassType())
3609 error("cast instruction to a non-primitive type: '" +
3610 DstTy->getDescription() + "'");
3611 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3612 $$.S.copy($4.S);
3613 delete $4.PAT;
3614 }
3615 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3616 if (!$2.V->getType()->isInteger() ||
3617 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3618 error("select condition must be bool");
3619 if ($4.V->getType() != $6.V->getType())
3620 error("select value types should match");
3621 $$.I = new SelectInst($2.V, $4.V, $6.V);
3622 $$.S.copy($4.S);
3623 }
3624 | VAARG ResolvedVal ',' Types {
3625 const Type *Ty = $4.PAT->get();
3626 NewVarArgs = true;
3627 $$.I = new VAArgInst($2.V, Ty);
3628 $$.S.copy($4.S);
3629 delete $4.PAT;
3630 }
3631 | VAARG_old ResolvedVal ',' Types {
3632 const Type* ArgTy = $2.V->getType();
3633 const Type* DstTy = $4.PAT->get();
3634 ObsoleteVarArgs = true;
3635 Function* NF = cast<Function>(CurModule.CurrentModule->
3636 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3637
3638 //b = vaarg a, t ->
3639 //foo = alloca 1 of t
3640 //bar = vacopy a
3641 //store bar -> foo
3642 //b = vaarg foo, t
3643 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3644 CurBB->getInstList().push_back(foo);
3645 CallInst* bar = new CallInst(NF, $2.V);
3646 CurBB->getInstList().push_back(bar);
3647 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3648 $$.I = new VAArgInst(foo, DstTy);
3649 $$.S.copy($4.S);
3650 delete $4.PAT;
3651 }
3652 | VANEXT_old ResolvedVal ',' Types {
3653 const Type* ArgTy = $2.V->getType();
3654 const Type* DstTy = $4.PAT->get();
3655 ObsoleteVarArgs = true;
3656 Function* NF = cast<Function>(CurModule.CurrentModule->
3657 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3658
3659 //b = vanext a, t ->
3660 //foo = alloca 1 of t
3661 //bar = vacopy a
3662 //store bar -> foo
3663 //tmp = vaarg foo, t
3664 //b = load foo
3665 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3666 CurBB->getInstList().push_back(foo);
3667 CallInst* bar = new CallInst(NF, $2.V);
3668 CurBB->getInstList().push_back(bar);
3669 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3670 Instruction* tmp = new VAArgInst(foo, DstTy);
3671 CurBB->getInstList().push_back(tmp);
3672 $$.I = new LoadInst(foo);
3673 $$.S.copy($4.S);
3674 delete $4.PAT;
3675 }
3676 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3677 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3678 error("Invalid extractelement operands");
3679 $$.I = new ExtractElementInst($2.V, $4.V);
3680 $$.S.copy($2.S.get(0));
3681 }
3682 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3683 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3684 error("Invalid insertelement operands");
3685 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3686 $$.S.copy($2.S);
3687 }
3688 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3689 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3690 error("Invalid shufflevector operands");
3691 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3692 $$.S.copy($2.S);
3693 }
3694 | PHI_TOK PHIList {
3695 const Type *Ty = $2.P->front().first->getType();
3696 if (!Ty->isFirstClassType())
3697 error("PHI node operands must be of first class type");
3698 PHINode *PHI = new PHINode(Ty);
3699 PHI->reserveOperandSpace($2.P->size());
3700 while ($2.P->begin() != $2.P->end()) {
3701 if ($2.P->front().first->getType() != Ty)
3702 error("All elements of a PHI node must be of the same type");
3703 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3704 $2.P->pop_front();
3705 }
3706 $$.I = PHI;
3707 $$.S.copy($2.S);
3708 delete $2.P; // Free the list...
3709 }
3710 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3711 // Handle the short call syntax
3712 const PointerType *PFTy;
3713 const FunctionType *FTy;
3714 Signedness FTySign;
3715 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3716 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3717 // Pull out the types of all of the arguments...
3718 std::vector<const Type*> ParamTypes;
3719 FTySign.makeComposite($3.S);
3720 if ($6) {
3721 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3722 I != E; ++I) {
3723 ParamTypes.push_back((*I).V->getType());
3724 FTySign.add(I->S);
3725 }
3726 }
3727
3728 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3729 if (isVarArg) ParamTypes.pop_back();
3730
3731 const Type *RetTy = $3.PAT->get();
3732 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3733 error("Functions cannot return aggregate types");
3734
3735 // Deal with CSRetCC
3736 ParamAttrsList *PAL = 0;
3737 if ($2 == OldCallingConv::CSRet) {
3738 ParamAttrsVector Attrs;
3739 ParamAttrsWithIndex PAWI;
3740 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
3741 Attrs.push_back(PAWI);
3742 PAL = ParamAttrsList::get(Attrs);
3743 }
3744
3745 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, PAL);
3746 PFTy = PointerType::get(FTy);
3747 $$.S.copy($3.S);
3748 } else {
3749 FTySign = $3.S;
3750 // Get the signedness of the result type. $3 is the pointer to the
3751 // function type so we get the 0th element to extract the function type,
3752 // and then the 0th element again to get the result type.
3753 $$.S.copy($3.S.get(0).get(0));
3754 }
3755 $4.S.makeComposite(FTySign);
3756
3757 // First upgrade any intrinsic calls.
3758 std::vector<Value*> Args;
3759 if ($6)
3760 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3761 Args.push_back((*$6)[i].V);
3762 Instruction *Inst = upgradeIntrinsicCall(FTy->getReturnType(), $4, Args);
3763
3764 // If we got an upgraded intrinsic
3765 if (Inst) {
3766 $$.I = Inst;
3767 } else {
3768 // Get the function we're calling
3769 Value *V = getVal(PFTy, $4);
3770
3771 // Check the argument values match
3772 if (!$6) { // Has no arguments?
3773 // Make sure no arguments is a good thing!
3774 if (FTy->getNumParams() != 0)
3775 error("No arguments passed to a function that expects arguments");
3776 } else { // Has arguments?
3777 // Loop through FunctionType's arguments and ensure they are specified
3778 // correctly!
3779 //
3780 FunctionType::param_iterator I = FTy->param_begin();
3781 FunctionType::param_iterator E = FTy->param_end();
3782 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3783
3784 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3785 if ((*ArgI).V->getType() != *I)
3786 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3787 (*I)->getDescription() + "'");
3788
3789 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3790 error("Invalid number of parameters detected");
3791 }
3792
3793 // Create the call instruction
David Greeneb1c4a7b2007-08-01 03:43:44 +00003794 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003795 CI->setTailCall($1);
3796 CI->setCallingConv(upgradeCallingConv($2));
3797 $$.I = CI;
3798 }
3799 delete $3.PAT;
3800 delete $6;
3801 lastCallingConv = OldCallingConv::C;
3802 }
3803 | MemoryInst {
3804 $$ = $1;
3805 }
3806 ;
3807
3808
3809// IndexList - List of indices for GEP based instructions...
3810IndexList
3811 : ',' ValueRefList { $$ = $2; }
3812 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3813 ;
3814
3815OptVolatile
3816 : VOLATILE { $$ = true; }
3817 | /* empty */ { $$ = false; }
3818 ;
3819
3820MemoryInst
3821 : MALLOC Types OptCAlign {
3822 const Type *Ty = $2.PAT->get();
3823 $$.S.makeComposite($2.S);
3824 $$.I = new MallocInst(Ty, 0, $3);
3825 delete $2.PAT;
3826 }
3827 | MALLOC Types ',' UINT ValueRef OptCAlign {
3828 const Type *Ty = $2.PAT->get();
3829 $5.S.makeUnsigned();
3830 $$.S.makeComposite($2.S);
3831 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3832 delete $2.PAT;
3833 }
3834 | ALLOCA Types OptCAlign {
3835 const Type *Ty = $2.PAT->get();
3836 $$.S.makeComposite($2.S);
3837 $$.I = new AllocaInst(Ty, 0, $3);
3838 delete $2.PAT;
3839 }
3840 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3841 const Type *Ty = $2.PAT->get();
3842 $5.S.makeUnsigned();
3843 $$.S.makeComposite($4.S);
3844 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3845 delete $2.PAT;
3846 }
3847 | FREE ResolvedVal {
3848 const Type *PTy = $2.V->getType();
3849 if (!isa<PointerType>(PTy))
3850 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3851 $$.I = new FreeInst($2.V);
3852 $$.S.makeSignless();
3853 }
3854 | OptVolatile LOAD Types ValueRef {
3855 const Type* Ty = $3.PAT->get();
3856 $4.S.copy($3.S);
3857 if (!isa<PointerType>(Ty))
3858 error("Can't load from nonpointer type: " + Ty->getDescription());
3859 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3860 error("Can't load from pointer of non-first-class type: " +
3861 Ty->getDescription());
3862 Value* tmpVal = getVal(Ty, $4);
3863 $$.I = new LoadInst(tmpVal, "", $1);
3864 $$.S.copy($3.S.get(0));
3865 delete $3.PAT;
3866 }
3867 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3868 $6.S.copy($5.S);
3869 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3870 if (!PTy)
3871 error("Can't store to a nonpointer type: " +
3872 $5.PAT->get()->getDescription());
3873 const Type *ElTy = PTy->getElementType();
3874 Value *StoreVal = $3.V;
3875 Value* tmpVal = getVal(PTy, $6);
3876 if (ElTy != $3.V->getType()) {
3877 StoreVal = handleSRetFuncTypeMerge($3.V, ElTy);
3878 if (!StoreVal)
3879 error("Can't store '" + $3.V->getType()->getDescription() +
3880 "' into space of type '" + ElTy->getDescription() + "'");
3881 else {
3882 PTy = PointerType::get(StoreVal->getType());
3883 if (Constant *C = dyn_cast<Constant>(tmpVal))
3884 tmpVal = ConstantExpr::getBitCast(C, PTy);
3885 else
3886 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3887 }
3888 }
3889 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3890 $$.S.makeSignless();
3891 delete $5.PAT;
3892 }
3893 | GETELEMENTPTR Types ValueRef IndexList {
3894 $3.S.copy($2.S);
3895 const Type* Ty = $2.PAT->get();
3896 if (!isa<PointerType>(Ty))
3897 error("getelementptr insn requires pointer operand");
3898
3899 std::vector<Value*> VIndices;
3900 upgradeGEPInstIndices(Ty, $4, VIndices);
3901
3902 Value* tmpVal = getVal(Ty, $3);
David Greene393be882007-09-04 15:46:09 +00003903 $$.I = new GetElementPtrInst(tmpVal, VIndices.begin(), VIndices.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003904 ValueInfo VI; VI.V = tmpVal; VI.S.copy($2.S);
3905 $$.S.copy(getElementSign(VI, VIndices));
3906 delete $2.PAT;
3907 delete $4;
3908 };
3909
3910
3911%%
3912
3913int yyerror(const char *ErrorMsg) {
3914 std::string where
3915 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3916 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3917 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3918 if (yychar != YYEMPTY && yychar != 0)
3919 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3920 "'.";
3921 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3922 std::cout << "llvm-upgrade: parse failed.\n";
3923 exit(1);
3924}
3925
3926void warning(const std::string& ErrorMsg) {
3927 std::string where
3928 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3929 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3930 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3931 if (yychar != YYEMPTY && yychar != 0)
3932 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3933 "'.";
3934 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3935}
3936
3937void error(const std::string& ErrorMsg, int LineNo) {
3938 if (LineNo == -1) LineNo = Upgradelineno;
3939 Upgradelineno = LineNo;
3940 yyerror(ErrorMsg.c_str());
3941}
3942