1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
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"
31 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
32 // relating to upreferences in the input stream.
34 //#define DEBUG_UPREFS 1
36 #define UR_OUT(X) std::cerr << X
41 #define YYERROR_VERBOSE 1
42 #define YYINCLUDED_STDLIB_H
48 int yyerror(const char*);
49 static void warning(const std::string& WarningMsg);
53 std::istream* LexInput;
54 static std::string CurFilename;
56 // This bool controls whether attributes are ever added to function declarations
57 // definitions and calls.
58 static bool AddAttributes = false;
60 static Module *ParserResult;
61 static bool ObsoleteVarArgs;
62 static bool NewVarArgs;
63 static BasicBlock *CurBB;
64 static GlobalVariable *CurGV;
65 static unsigned lastCallingConv;
67 // This contains info used when building the body of a function. It is
68 // destroyed when the function is completed.
70 typedef std::vector<Value *> ValueList; // Numbered defs
72 typedef std::pair<std::string,TypeInfo> RenameMapKey;
73 typedef std::map<RenameMapKey,std::string> RenameMapType;
76 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
77 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
79 static 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;
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;
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.
102 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
104 GlobalRefsType GlobalRefs;
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.
111 ResolveDefinitions(LateResolveValues);
113 // Check to make sure that all global value forward references have been
116 if (!GlobalRefs.empty()) {
117 std::string UndefinedReferences = "Unresolved global references exist:\n";
119 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
121 UndefinedReferences += " " + I->first.first->getDescription() + " " +
122 I->first.second.getName() + "\n";
124 error(UndefinedReferences);
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())
135 dataLayout.append(PointerSize == Module::Pointer64 ?
136 "p:64:64" : "p:32:32");
138 CurrentModule->setDataLayout(dataLayout);
141 Values.clear(); // Clear out function local definitions
144 NamedTypeSigns.clear();
145 NamedValueSigns.clear();
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()) {
163 void setEndianness(Module::Endianness E) { Endian = E; }
164 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
167 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
168 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
170 static struct PerFunctionInfo {
171 Function *CurrentFunction; // Pointer to current function being created
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.
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;
185 inline PerFunctionInfo() {
188 Linkage = GlobalValue::ExternalLinkage;
191 inline void FunctionStart(Function *M) {
196 void FunctionDone() {
197 NumberedBlocks.clear();
199 // Any forward referenced blocks left?
200 if (!BBForwardRefs.empty()) {
201 error("Undefined reference to label " +
202 BBForwardRefs.begin()->first->getName());
206 // Resolve all forward references now.
207 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
209 Values.clear(); // Clear out function local definitions
213 Linkage = GlobalValue::ExternalLinkage;
215 } CurFun; // Info for the current function...
217 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
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
224 static RenameMapKey makeRenameMapKey(const std::string &Name, const Type* Ty,
225 const Signedness &Sign) {
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()]);
234 return std::make_pair(Name, TI);
238 //===----------------------------------------------------------------------===//
239 // Code to handle definitions of all the types
240 //===----------------------------------------------------------------------===//
242 static int InsertValue(Value *V,
243 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
244 if (V->hasName()) return -1; // Is this a numbered definition?
246 // Yes, insert the value into the value table...
247 ValueList &List = ValueTab[V->getType()];
249 return List.size()-1;
252 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
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];
260 case ValID::NameVal: // Is it a named definition?
261 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
266 error("Internal parser error: Invalid symbol type reference");
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...
274 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
276 if (inFunctionScope()) {
277 if (D.Type == ValID::NameVal) {
278 error("Reference to an undefined type: '" + D.getName() + "'");
281 error("Reference to an undefined type: #" + itostr(D.Num));
286 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
287 if (I != CurModule.LateResolveTypes.end())
290 Type *Typ = OpaqueType::get();
291 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
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
298 static Signedness getTypeSign(const ValID &D) {
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];
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())
311 // Perhaps its a named forward .. just cache the name
319 // If we don't find it, its signless
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.
330 static 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");
337 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
338 if (CurIdx == Indices.size())
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())
346 assert(S.isComposite() && "Bad Signedness type");
347 if (isa<StructType>(CT)) {
348 S = S.get(cast<ConstantInt>(Index)->getZExtValue());
353 S = CurModule.NamedTypeSigns[S.getName()];
356 Result.makeComposite(S);
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.
363 static Signedness getElementSign(const ConstInfo& CI,
364 const std::vector<Constant*> &Indices) {
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);
376 // getExistingValue - Look up the value specified by the provided type and
377 // the provided ValID. If the value exists and has already been defined, return
378 // it. Otherwise return null.
380 static Value *getExistingValue(const Type *Ty, const ValID &D) {
381 if (isa<FunctionType>(Ty)) {
382 error("Functions are not values and must be referenced as pointers");
386 case ValID::NumberVal: { // Is it a numbered definition?
387 unsigned Num = (unsigned)D.Num;
389 // Module constants occupy the lowest numbered slots...
390 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
391 if (VI != CurModule.Values.end()) {
392 if (Num < VI->second.size())
393 return VI->second[Num];
394 Num -= VI->second.size();
397 // Make sure that our type is within bounds
398 VI = CurFun.Values.find(Ty);
399 if (VI == CurFun.Values.end()) return 0;
401 // Check that the number is within bounds...
402 if (VI->second.size() <= Num) return 0;
404 return VI->second[Num];
407 case ValID::NameVal: { // Is it a named definition?
408 // Get the name out of the ID
409 RenameMapKey Key = makeRenameMapKey(D.Name, Ty, D.S);
411 if (inFunctionScope()) {
412 // See if the name was renamed
413 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
414 std::string LookupName;
415 if (I != CurFun.RenameMap.end())
416 LookupName = I->second;
419 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
420 V = SymTab.lookup(LookupName);
421 if (V && V->getType() != Ty)
425 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
426 std::string LookupName;
427 if (I != CurModule.RenameMap.end())
428 LookupName = I->second;
431 V = CurModule.CurrentModule->getValueSymbolTable().lookup(LookupName);
432 if (V && V->getType() != Ty)
438 D.destroy(); // Free old strdup'd memory...
442 // Check to make sure that "Ty" is an integral type, and that our
443 // value will fit into the specified type...
444 case ValID::ConstSIntVal: // Is it a constant pool reference??
445 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
446 error("Signed integral constant '" + itostr(D.ConstPool64) +
447 "' is invalid for type '" + Ty->getDescription() + "'");
449 return ConstantInt::get(Ty, D.ConstPool64);
451 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
452 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
453 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
454 error("Integral constant '" + utostr(D.UConstPool64) +
455 "' is invalid or out of range");
456 else // This is really a signed reference. Transmogrify.
457 return ConstantInt::get(Ty, D.ConstPool64);
459 return ConstantInt::get(Ty, D.UConstPool64);
461 case ValID::ConstFPVal: // Is it a floating point const pool reference?
462 if (!ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP))
463 error("FP constant invalid for type");
464 // Lexer has no type info, so builds all FP constants as double.
466 if (Ty==Type::FloatTy)
467 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
468 return ConstantFP::get(Ty, *D.ConstPoolFP);
470 case ValID::ConstNullVal: // Is it a null value?
471 if (!isa<PointerType>(Ty))
472 error("Cannot create a a non pointer null");
473 return ConstantPointerNull::get(cast<PointerType>(Ty));
475 case ValID::ConstUndefVal: // Is it an undef value?
476 return UndefValue::get(Ty);
478 case ValID::ConstZeroVal: // Is it a zero value?
479 return Constant::getNullValue(Ty);
481 case ValID::ConstantVal: // Fully resolved constant?
482 if (D.ConstantValue->getType() != Ty)
483 error("Constant expression type different from required type");
484 return D.ConstantValue;
486 case ValID::InlineAsmVal: { // Inline asm expression
487 const PointerType *PTy = dyn_cast<PointerType>(Ty);
488 const FunctionType *FTy =
489 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
490 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
491 error("Invalid type for asm constraint string");
492 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
493 D.IAD->HasSideEffects);
494 D.destroy(); // Free InlineAsmDescriptor.
498 assert(0 && "Unhandled case");
502 assert(0 && "Unhandled case");
506 // getVal - This function is identical to getExistingValue, except that if a
507 // value is not already defined, it "improvises" by creating a placeholder var
508 // that looks and acts just like the requested variable. When the value is
509 // defined later, all uses of the placeholder variable are replaced with the
512 static Value *getVal(const Type *Ty, const ValID &ID) {
513 if (Ty == Type::LabelTy)
514 error("Cannot use a basic block here");
516 // See if the value has already been defined.
517 Value *V = getExistingValue(Ty, ID);
520 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
521 error("Invalid use of a composite type");
523 // If we reached here, we referenced either a symbol that we don't know about
524 // or an id number that hasn't been read yet. We may be referencing something
525 // forward, so just create an entry to be resolved later and get to it...
526 V = new Argument(Ty);
528 // Remember where this forward reference came from. FIXME, shouldn't we try
529 // to recycle these things??
530 CurModule.PlaceHolderInfo.insert(
531 std::make_pair(V, std::make_pair(ID, Upgradelineno)));
533 if (inFunctionScope())
534 InsertValue(V, CurFun.LateResolveValues);
536 InsertValue(V, CurModule.LateResolveValues);
540 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
541 static std::string makeNameUnique(const std::string& Name) {
542 static unsigned UniqueNameCounter = 1;
543 std::string Result(Name);
544 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
548 /// getBBVal - This is used for two purposes:
549 /// * If isDefinition is true, a new basic block with the specified ID is being
551 /// * If isDefinition is true, this is a reference to a basic block, which may
552 /// or may not be a forward reference.
554 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
555 assert(inFunctionScope() && "Can't get basic block at global scope");
561 error("Illegal label reference " + ID.getName());
563 case ValID::NumberVal: // Is it a numbered definition?
564 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
565 CurFun.NumberedBlocks.resize(ID.Num+1);
566 BB = CurFun.NumberedBlocks[ID.Num];
568 case ValID::NameVal: // Is it a named definition?
570 if (Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name)) {
571 if (N->getType() != Type::LabelTy) {
572 // Register names didn't use to conflict with basic block names
573 // because of type planes. Now they all have to be unique. So, we just
574 // rename the register and treat this name as if no basic block
576 RenameMapKey Key = makeRenameMapKey(ID.Name, N->getType(), ID.S);
577 N->setName(makeNameUnique(N->getName()));
578 CurModule.RenameMap[Key] = N->getName();
581 BB = cast<BasicBlock>(N);
587 // See if the block has already been defined.
589 // If this is the definition of the block, make sure the existing value was
590 // just a forward reference. If it was a forward reference, there will be
591 // an entry for it in the PlaceHolderInfo map.
592 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
593 // The existing value was a definition, not a forward reference.
594 error("Redefinition of label " + ID.getName());
596 ID.destroy(); // Free strdup'd memory.
600 // Otherwise this block has not been seen before.
601 BB = new BasicBlock("", CurFun.CurrentFunction);
602 if (ID.Type == ValID::NameVal) {
603 BB->setName(ID.Name);
605 CurFun.NumberedBlocks[ID.Num] = BB;
608 // If this is not a definition, keep track of it so we can use it as a forward
611 // Remember where this forward reference came from.
612 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
614 // The forward declaration could have been inserted anywhere in the
615 // function: insert it into the correct place now.
616 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
617 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
624 //===----------------------------------------------------------------------===//
625 // Code to handle forward references in instructions
626 //===----------------------------------------------------------------------===//
628 // This code handles the late binding needed with statements that reference
629 // values not defined yet... for example, a forward branch, or the PHI node for
632 // This keeps a table (CurFun.LateResolveValues) of all such forward references
633 // and back patchs after we are done.
636 // ResolveDefinitions - If we could not resolve some defs at parsing
637 // time (forward branches, phi functions for loops, etc...) resolve the
641 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
642 std::map<const Type*,ValueList> *FutureLateResolvers) {
644 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
645 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
646 E = LateResolvers.end(); LRI != E; ++LRI) {
647 const Type* Ty = LRI->first;
648 ValueList &List = LRI->second;
649 while (!List.empty()) {
650 Value *V = List.back();
653 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
654 CurModule.PlaceHolderInfo.find(V);
655 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
657 ValID &DID = PHI->second.first;
659 Value *TheRealValue = getExistingValue(Ty, DID);
661 V->replaceAllUsesWith(TheRealValue);
663 CurModule.PlaceHolderInfo.erase(PHI);
664 } else if (FutureLateResolvers) {
665 // Functions have their unresolved items forwarded to the module late
667 InsertValue(V, *FutureLateResolvers);
669 if (DID.Type == ValID::NameVal) {
670 error("Reference to an invalid definition: '" + DID.getName() +
671 "' of type '" + V->getType()->getDescription() + "'",
675 error("Reference to an invalid definition: #" +
676 itostr(DID.Num) + " of type '" +
677 V->getType()->getDescription() + "'", PHI->second.second);
684 LateResolvers.clear();
687 /// This function is used for type resolution and upref handling. When a type
688 /// becomes concrete, this function is called to adjust the signedness for the
690 static void ResolveTypeSign(const Type* oldTy, const Signedness &Sign) {
691 std::string TyName = CurModule.CurrentModule->getTypeName(oldTy);
693 CurModule.NamedTypeSigns[TyName] = Sign;
696 /// ResolveTypeTo - A brand new type was just declared. This means that (if
697 /// name is not null) things referencing Name can be resolved. Otherwise,
698 /// things refering to the number can be resolved. Do this now.
699 static void ResolveTypeTo(char *Name, const Type *ToTy, const Signedness& Sign){
702 D = ValID::create(Name);
704 D = ValID::create((int)CurModule.Types.size());
708 CurModule.NamedTypeSigns[Name] = Sign;
710 std::map<ValID, PATypeHolder>::iterator I =
711 CurModule.LateResolveTypes.find(D);
712 if (I != CurModule.LateResolveTypes.end()) {
713 const Type *OldTy = I->second.get();
714 ((DerivedType*)OldTy)->refineAbstractTypeTo(ToTy);
715 CurModule.LateResolveTypes.erase(I);
719 /// This is the implementation portion of TypeHasInteger. It traverses the
720 /// type given, avoiding recursive types, and returns true as soon as it finds
721 /// an integer type. If no integer type is found, it returns false.
722 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
723 // Handle some easy cases
724 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
728 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
729 return STy->getElementType()->isInteger();
731 // Avoid type structure recursion
732 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
737 // Push us on the type stack
740 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
741 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
743 FunctionType::param_iterator I = FTy->param_begin();
744 FunctionType::param_iterator E = FTy->param_end();
746 if (TypeHasIntegerI(*I, Stack))
749 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
750 StructType::element_iterator I = STy->element_begin();
751 StructType::element_iterator E = STy->element_end();
752 for (; I != E; ++I) {
753 if (TypeHasIntegerI(*I, Stack))
758 // There shouldn't be anything else, but its definitely not integer
759 assert(0 && "What type is this?");
763 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
764 /// to avoid recursion, and then calls TypeHasIntegerI.
765 static inline bool TypeHasInteger(const Type *Ty) {
766 std::vector<const Type*> TyStack;
767 return TypeHasIntegerI(Ty, TyStack);
770 // setValueName - Set the specified value to the name given. The name may be
771 // null potentially, in which case this is a noop. The string passed in is
772 // assumed to be a malloc'd string buffer, and is free'd by this function.
774 static void setValueName(const ValueInfo &V, char *NameStr) {
776 std::string Name(NameStr); // Copy string
777 free(NameStr); // Free old string
779 if (V.V->getType() == Type::VoidTy) {
780 error("Can't assign name '" + Name + "' to value with void type");
784 assert(inFunctionScope() && "Must be in function scope");
786 // Search the function's symbol table for an existing value of this name
787 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
788 Value* Existing = ST.lookup(Name);
790 // An existing value of the same name was found. This might have happened
791 // because of the integer type planes collapsing in LLVM 2.0.
792 if (Existing->getType() == V.V->getType() &&
793 !TypeHasInteger(Existing->getType())) {
794 // If the type does not contain any integers in them then this can't be
795 // a type plane collapsing issue. It truly is a redefinition and we
796 // should error out as the assembly is invalid.
797 error("Redefinition of value named '" + Name + "' of type '" +
798 V.V->getType()->getDescription() + "'");
801 // In LLVM 2.0 we don't allow names to be re-used for any values in a
802 // function, regardless of Type. Previously re-use of names was okay as
803 // long as they were distinct types. With type planes collapsing because
804 // of the signedness change and because of PR411, this can no longer be
805 // supported. We must search the entire symbol table for a conflicting
806 // name and make the name unique. No warning is needed as this can't
808 std::string NewName = makeNameUnique(Name);
809 // We're changing the name but it will probably be used by other
810 // instructions as operands later on. Consequently we have to retain
811 // a mapping of the renaming that we're doing.
812 RenameMapKey Key = makeRenameMapKey(Name, V.V->getType(), V.S);
813 CurFun.RenameMap[Key] = NewName;
822 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
823 /// this is a declaration, otherwise it is a definition.
824 static GlobalVariable *
825 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
826 bool isConstantGlobal, const Type *Ty,
827 Constant *Initializer,
828 const Signedness &Sign) {
829 if (isa<FunctionType>(Ty))
830 error("Cannot declare global vars of function type");
832 const PointerType *PTy = PointerType::getUnqual(Ty);
836 Name = NameStr; // Copy string
837 free(NameStr); // Free old string
840 // See if this global value was forward referenced. If so, recycle the
844 ID = ValID::create((char*)Name.c_str());
846 ID = ValID::create((int)CurModule.Values[PTy].size());
848 ID.S.makeComposite(Sign);
850 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
851 // Move the global to the end of the list, from whereever it was
852 // previously inserted.
853 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
854 CurModule.CurrentModule->getGlobalList().remove(GV);
855 CurModule.CurrentModule->getGlobalList().push_back(GV);
856 GV->setInitializer(Initializer);
857 GV->setLinkage(Linkage);
858 GV->setConstant(isConstantGlobal);
859 InsertValue(GV, CurModule.Values);
863 // If this global has a name, check to see if there is already a definition
864 // of this global in the module and emit warnings if there are conflicts.
866 // The global has a name. See if there's an existing one of the same name.
867 if (CurModule.CurrentModule->getNamedGlobal(Name) ||
868 CurModule.CurrentModule->getFunction(Name)) {
869 // We found an existing global of the same name. This isn't allowed
870 // in LLVM 2.0. Consequently, we must alter the name of the global so it
871 // can at least compile. This can happen because of type planes
872 // There is alread a global of the same name which means there is a
873 // conflict. Let's see what we can do about it.
874 std::string NewName(makeNameUnique(Name));
875 if (Linkage != GlobalValue::InternalLinkage) {
876 // The linkage of this gval is external so we can't reliably rename
877 // it because it could potentially create a linking problem.
878 // However, we can't leave the name conflict in the output either or
879 // it won't assemble with LLVM 2.0. So, all we can do is rename
880 // this one to something unique and emit a warning about the problem.
881 warning("Renaming global variable '" + Name + "' to '" + NewName +
882 "' may cause linkage errors");
885 // Put the renaming in the global rename map
887 makeRenameMapKey(Name, PointerType::getUnqual(Ty), ID.S);
888 CurModule.RenameMap[Key] = NewName;
895 // Otherwise there is no existing GV to use, create one now.
897 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
898 CurModule.CurrentModule);
899 InsertValue(GV, CurModule.Values);
900 // Remember the sign of this global.
901 CurModule.NamedValueSigns[Name] = ID.S;
905 // setTypeName - Set the specified type to the name given. The name may be
906 // null potentially, in which case this is a noop. The string passed in is
907 // assumed to be a malloc'd string buffer, and is freed by this function.
909 // This function returns true if the type has already been defined, but is
910 // allowed to be redefined in the specified context. If the name is a new name
911 // for the type plane, it is inserted and false is returned.
912 static bool setTypeName(const PATypeInfo& TI, char *NameStr) {
913 assert(!inFunctionScope() && "Can't give types function-local names");
914 if (NameStr == 0) return false;
916 std::string Name(NameStr); // Copy string
917 free(NameStr); // Free old string
919 const Type* Ty = TI.PAT->get();
921 // We don't allow assigning names to void type
922 if (Ty == Type::VoidTy) {
923 error("Can't assign name '" + Name + "' to the void type");
927 // Set the type name, checking for conflicts as we do so.
928 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, Ty);
930 // Save the sign information for later use
931 CurModule.NamedTypeSigns[Name] = TI.S;
933 if (AlreadyExists) { // Inserting a name that is already defined???
934 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
935 assert(Existing && "Conflict but no matching type?");
937 // There is only one case where this is allowed: when we are refining an
938 // opaque type. In this case, Existing will be an opaque type.
939 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
940 // We ARE replacing an opaque type!
941 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(Ty);
945 // Otherwise, this is an attempt to redefine a type. That's okay if
946 // the redefinition is identical to the original. This will be so if
947 // Existing and T point to the same Type object. In this one case we
948 // allow the equivalent redefinition.
949 if (Existing == Ty) return true; // Yes, it's equal.
951 // Any other kind of (non-equivalent) redefinition is an error.
952 error("Redefinition of type named '" + Name + "' in the '" +
953 Ty->getDescription() + "' type plane");
959 //===----------------------------------------------------------------------===//
960 // Code for handling upreferences in type names...
963 // TypeContains - Returns true if Ty directly contains E in it.
965 static bool TypeContains(const Type *Ty, const Type *E) {
966 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
967 E) != Ty->subtype_end();
972 // NestingLevel - The number of nesting levels that need to be popped before
973 // this type is resolved.
974 unsigned NestingLevel;
976 // LastContainedTy - This is the type at the current binding level for the
977 // type. Every time we reduce the nesting level, this gets updated.
978 const Type *LastContainedTy;
980 // UpRefTy - This is the actual opaque type that the upreference is
984 UpRefRecord(unsigned NL, OpaqueType *URTy)
985 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) { }
989 // UpRefs - A list of the outstanding upreferences that need to be resolved.
990 static std::vector<UpRefRecord> UpRefs;
992 /// HandleUpRefs - Every time we finish a new layer of types, this function is
993 /// called. It loops through the UpRefs vector, which is a list of the
994 /// currently active types. For each type, if the up reference is contained in
995 /// the newly completed type, we decrement the level count. When the level
996 /// count reaches zero, the upreferenced type is the type that is passed in:
997 /// thus we can complete the cycle.
999 static PATypeHolder HandleUpRefs(const Type *ty, const Signedness& Sign) {
1000 // If Ty isn't abstract, or if there are no up-references in it, then there is
1001 // nothing to resolve here.
1002 if (!ty->isAbstract() || UpRefs.empty()) return ty;
1004 PATypeHolder Ty(ty);
1005 UR_OUT("Type '" << Ty->getDescription() <<
1006 "' newly formed. Resolving upreferences.\n" <<
1007 UpRefs.size() << " upreferences active!\n");
1009 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
1010 // to zero), we resolve them all together before we resolve them to Ty. At
1011 // the end of the loop, if there is anything to resolve to Ty, it will be in
1013 OpaqueType *TypeToResolve = 0;
1016 for (; i != UpRefs.size(); ++i) {
1017 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
1018 << UpRefs[i].UpRefTy->getDescription() << ") = "
1019 << (TypeContains(Ty, UpRefs[i].UpRefTy) ? "true" : "false") << "\n");
1020 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
1021 // Decrement level of upreference
1022 unsigned Level = --UpRefs[i].NestingLevel;
1023 UpRefs[i].LastContainedTy = Ty;
1024 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
1025 if (Level == 0) { // Upreference should be resolved!
1026 if (!TypeToResolve) {
1027 TypeToResolve = UpRefs[i].UpRefTy;
1029 UR_OUT(" * Resolving upreference for "
1030 << UpRefs[i].UpRefTy->getDescription() << "\n";
1031 std::string OldName = UpRefs[i].UpRefTy->getDescription());
1032 ResolveTypeSign(UpRefs[i].UpRefTy, Sign);
1033 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
1034 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
1035 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
1037 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
1038 --i; // Do not skip the next element...
1043 if (TypeToResolve) {
1044 UR_OUT(" * Resolving upreference for "
1045 << UpRefs[i].UpRefTy->getDescription() << "\n";
1046 std::string OldName = TypeToResolve->getDescription());
1047 ResolveTypeSign(TypeToResolve, Sign);
1048 TypeToResolve->refineAbstractTypeTo(Ty);
1054 bool Signedness::operator<(const Signedness &that) const {
1057 return *(this->name) < *(that.name);
1059 return CurModule.NamedTypeSigns[*name] < that;
1060 } else if (that.isNamed()) {
1061 return *this < CurModule.NamedTypeSigns[*that.name];
1064 if (isComposite() && that.isComposite()) {
1065 if (sv->size() == that.sv->size()) {
1066 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1067 SignVector::const_iterator thatI = that.sv->begin(),
1068 thatE = that.sv->end();
1069 for (; thisI != thisE; ++thisI, ++thatI) {
1070 if (*thisI < *thatI)
1072 else if (!(*thisI == *thatI))
1077 return sv->size() < that.sv->size();
1079 return kind < that.kind;
1082 bool Signedness::operator==(const Signedness &that) const {
1085 return *(this->name) == *(that.name);
1087 return CurModule.NamedTypeSigns[*(this->name)] == that;
1088 else if (that.isNamed())
1089 return *this == CurModule.NamedTypeSigns[*(that.name)];
1090 if (isComposite() && that.isComposite()) {
1091 if (sv->size() == that.sv->size()) {
1092 SignVector::const_iterator thisI = sv->begin(), thisE = sv->end();
1093 SignVector::const_iterator thatI = that.sv->begin(),
1094 thatE = that.sv->end();
1095 for (; thisI != thisE; ++thisI, ++thatI) {
1096 if (!(*thisI == *thatI))
1103 return kind == that.kind;
1106 void Signedness::copy(const Signedness &that) {
1107 if (that.isNamed()) {
1109 name = new std::string(*that.name);
1110 } else if (that.isComposite()) {
1112 sv = new SignVector();
1120 void Signedness::destroy() {
1123 } else if (isComposite()) {
1129 void Signedness::dump() const {
1130 if (isComposite()) {
1131 if (sv->size() == 1) {
1136 for (unsigned i = 0; i < sv->size(); ++i) {
1143 } else if (isNamed()) {
1145 } else if (isSigned()) {
1147 } else if (isUnsigned()) {
1154 static inline Instruction::TermOps
1155 getTermOp(TermOps op) {
1157 default : assert(0 && "Invalid OldTermOp");
1158 case RetOp : return Instruction::Ret;
1159 case BrOp : return Instruction::Br;
1160 case SwitchOp : return Instruction::Switch;
1161 case InvokeOp : return Instruction::Invoke;
1162 case UnwindOp : return Instruction::Unwind;
1163 case UnreachableOp: return Instruction::Unreachable;
1167 static inline Instruction::BinaryOps
1168 getBinaryOp(BinaryOps op, const Type *Ty, const Signedness& Sign) {
1170 default : assert(0 && "Invalid OldBinaryOps");
1176 case SetGT : assert(0 && "Should use getCompareOp");
1177 case AddOp : return Instruction::Add;
1178 case SubOp : return Instruction::Sub;
1179 case MulOp : return Instruction::Mul;
1181 // This is an obsolete instruction so we must upgrade it based on the
1182 // types of its operands.
1183 bool isFP = Ty->isFloatingPoint();
1184 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1185 // If its a vector type we want to use the element type
1186 isFP = PTy->getElementType()->isFloatingPoint();
1188 return Instruction::FDiv;
1189 else if (Sign.isSigned())
1190 return Instruction::SDiv;
1191 return Instruction::UDiv;
1193 case UDivOp : return Instruction::UDiv;
1194 case SDivOp : return Instruction::SDiv;
1195 case FDivOp : return Instruction::FDiv;
1197 // This is an obsolete instruction so we must upgrade it based on the
1198 // types of its operands.
1199 bool isFP = Ty->isFloatingPoint();
1200 if (const VectorType* PTy = dyn_cast<VectorType>(Ty))
1201 // If its a vector type we want to use the element type
1202 isFP = PTy->getElementType()->isFloatingPoint();
1203 // Select correct opcode
1205 return Instruction::FRem;
1206 else if (Sign.isSigned())
1207 return Instruction::SRem;
1208 return Instruction::URem;
1210 case URemOp : return Instruction::URem;
1211 case SRemOp : return Instruction::SRem;
1212 case FRemOp : return Instruction::FRem;
1213 case LShrOp : return Instruction::LShr;
1214 case AShrOp : return Instruction::AShr;
1215 case ShlOp : return Instruction::Shl;
1217 if (Sign.isSigned())
1218 return Instruction::AShr;
1219 return Instruction::LShr;
1220 case AndOp : return Instruction::And;
1221 case OrOp : return Instruction::Or;
1222 case XorOp : return Instruction::Xor;
1226 static inline Instruction::OtherOps
1227 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
1228 const Signedness &Sign) {
1229 bool isSigned = Sign.isSigned();
1230 bool isFP = Ty->isFloatingPoint();
1232 default : assert(0 && "Invalid OldSetCC");
1235 predicate = FCmpInst::FCMP_OEQ;
1236 return Instruction::FCmp;
1238 predicate = ICmpInst::ICMP_EQ;
1239 return Instruction::ICmp;
1243 predicate = FCmpInst::FCMP_UNE;
1244 return Instruction::FCmp;
1246 predicate = ICmpInst::ICMP_NE;
1247 return Instruction::ICmp;
1251 predicate = FCmpInst::FCMP_OLE;
1252 return Instruction::FCmp;
1255 predicate = ICmpInst::ICMP_SLE;
1257 predicate = ICmpInst::ICMP_ULE;
1258 return Instruction::ICmp;
1262 predicate = FCmpInst::FCMP_OGE;
1263 return Instruction::FCmp;
1266 predicate = ICmpInst::ICMP_SGE;
1268 predicate = ICmpInst::ICMP_UGE;
1269 return Instruction::ICmp;
1273 predicate = FCmpInst::FCMP_OLT;
1274 return Instruction::FCmp;
1277 predicate = ICmpInst::ICMP_SLT;
1279 predicate = ICmpInst::ICMP_ULT;
1280 return Instruction::ICmp;
1284 predicate = FCmpInst::FCMP_OGT;
1285 return Instruction::FCmp;
1288 predicate = ICmpInst::ICMP_SGT;
1290 predicate = ICmpInst::ICMP_UGT;
1291 return Instruction::ICmp;
1296 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1298 default : assert(0 && "Invalid OldMemoryOps");
1299 case MallocOp : return Instruction::Malloc;
1300 case FreeOp : return Instruction::Free;
1301 case AllocaOp : return Instruction::Alloca;
1302 case LoadOp : return Instruction::Load;
1303 case StoreOp : return Instruction::Store;
1304 case GetElementPtrOp : return Instruction::GetElementPtr;
1308 static inline Instruction::OtherOps
1309 getOtherOp(OtherOps op, const Signedness &Sign) {
1311 default : assert(0 && "Invalid OldOtherOps");
1312 case PHIOp : return Instruction::PHI;
1313 case CallOp : return Instruction::Call;
1314 case SelectOp : return Instruction::Select;
1315 case UserOp1 : return Instruction::UserOp1;
1316 case UserOp2 : return Instruction::UserOp2;
1317 case VAArg : return Instruction::VAArg;
1318 case ExtractElementOp : return Instruction::ExtractElement;
1319 case InsertElementOp : return Instruction::InsertElement;
1320 case ShuffleVectorOp : return Instruction::ShuffleVector;
1321 case ICmpOp : return Instruction::ICmp;
1322 case FCmpOp : return Instruction::FCmp;
1326 static inline Value*
1327 getCast(CastOps op, Value *Src, const Signedness &SrcSign, const Type *DstTy,
1328 const Signedness &DstSign, bool ForceInstruction = false) {
1329 Instruction::CastOps Opcode;
1330 const Type* SrcTy = Src->getType();
1332 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1333 // fp -> ptr cast is no longer supported but we must upgrade this
1334 // by doing a double cast: fp -> int -> ptr
1335 SrcTy = Type::Int64Ty;
1336 Opcode = Instruction::IntToPtr;
1337 if (isa<Constant>(Src)) {
1338 Src = ConstantExpr::getCast(Instruction::FPToUI,
1339 cast<Constant>(Src), SrcTy);
1341 std::string NewName(makeNameUnique(Src->getName()));
1342 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1344 } else if (isa<IntegerType>(DstTy) &&
1345 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1346 // cast type %x to bool was previously defined as setne type %x, null
1347 // The cast semantic is now to truncate, not compare so we must retain
1348 // the original intent by replacing the cast with a setne
1349 Constant* Null = Constant::getNullValue(SrcTy);
1350 Instruction::OtherOps Opcode = Instruction::ICmp;
1351 unsigned short predicate = ICmpInst::ICMP_NE;
1352 if (SrcTy->isFloatingPoint()) {
1353 Opcode = Instruction::FCmp;
1354 predicate = FCmpInst::FCMP_ONE;
1355 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1356 error("Invalid cast to bool");
1358 if (isa<Constant>(Src) && !ForceInstruction)
1359 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1361 return CmpInst::create(Opcode, predicate, Src, Null);
1363 // Determine the opcode to use by calling CastInst::getCastOpcode
1365 CastInst::getCastOpcode(Src, SrcSign.isSigned(), DstTy,
1366 DstSign.isSigned());
1368 } else switch (op) {
1369 default: assert(0 && "Invalid cast token");
1370 case TruncOp: Opcode = Instruction::Trunc; break;
1371 case ZExtOp: Opcode = Instruction::ZExt; break;
1372 case SExtOp: Opcode = Instruction::SExt; break;
1373 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1374 case FPExtOp: Opcode = Instruction::FPExt; break;
1375 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1376 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1377 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1378 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1379 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1380 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1381 case BitCastOp: Opcode = Instruction::BitCast; break;
1384 if (isa<Constant>(Src) && !ForceInstruction)
1385 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1386 return CastInst::create(Opcode, Src, DstTy);
1389 static Instruction *
1390 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1391 std::vector<Value*>& Args) {
1393 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1394 if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' ||
1395 Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.')
1400 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1401 if (Args.size() != 2)
1402 error("Invalid prototype for " + Name);
1403 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1408 const Type* PtrTy = PointerType::getUnqual(Type::Int8Ty);
1409 std::vector<const Type*> Params;
1410 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1411 if (Args.size() != 1)
1412 error("Invalid prototype for " + Name + " prototype");
1413 Params.push_back(PtrTy);
1414 const FunctionType *FTy =
1415 FunctionType::get(Type::VoidTy, Params, false);
1416 const PointerType *PFTy = PointerType::getUnqual(FTy);
1417 Value* Func = getVal(PFTy, ID);
1418 Args[0] = new BitCastInst(Args[0], PtrTy, makeNameUnique("va"), CurBB);
1419 return new CallInst(Func, Args.begin(), Args.end());
1420 } else if (Name == "llvm.va_copy") {
1421 if (Args.size() != 2)
1422 error("Invalid prototype for " + Name + " prototype");
1423 Params.push_back(PtrTy);
1424 Params.push_back(PtrTy);
1425 const FunctionType *FTy =
1426 FunctionType::get(Type::VoidTy, Params, false);
1427 const PointerType *PFTy = PointerType::getUnqual(FTy);
1428 Value* Func = getVal(PFTy, ID);
1429 std::string InstName0(makeNameUnique("va0"));
1430 std::string InstName1(makeNameUnique("va1"));
1431 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1432 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1433 return new CallInst(Func, Args.begin(), Args.end());
1440 const Type* upgradeGEPCEIndices(const Type* PTy,
1441 std::vector<ValueInfo> *Indices,
1442 std::vector<Constant*> &Result) {
1443 const Type *Ty = PTy;
1445 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1446 Constant *Index = cast<Constant>((*Indices)[i].V);
1448 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1449 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1450 // struct indices to i32 struct indices with ZExt for compatibility.
1451 if (CI->getBitWidth() < 32)
1452 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1455 if (isa<SequentialType>(Ty)) {
1456 // Make sure that unsigned SequentialType indices are zext'd to
1457 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1458 // all indices for SequentialType elements. We must retain the same
1459 // semantic (zext) for unsigned types.
1460 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1461 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1462 Index = ConstantExpr::getCast(Instruction::ZExt, Index,Type::Int64Ty);
1466 Result.push_back(Index);
1467 Ty = GetElementPtrInst::getIndexedType(PTy, Result.begin(),
1470 error("Index list invalid for constant getelementptr");
1475 const Type* upgradeGEPInstIndices(const Type* PTy,
1476 std::vector<ValueInfo> *Indices,
1477 std::vector<Value*> &Result) {
1478 const Type *Ty = PTy;
1480 for (unsigned i = 0, e = Indices->size(); i != e ; ++i) {
1481 Value *Index = (*Indices)[i].V;
1483 if (ConstantInt *CI = dyn_cast<ConstantInt>(Index)) {
1484 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1485 // struct indices to i32 struct indices with ZExt for compatibility.
1486 if (CI->getBitWidth() < 32)
1487 Index = ConstantExpr::getCast(Instruction::ZExt, CI, Type::Int32Ty);
1491 if (isa<StructType>(Ty)) { // Only change struct indices
1492 if (!isa<Constant>(Index)) {
1493 error("Invalid non-constant structure index");
1497 // Make sure that unsigned SequentialType indices are zext'd to
1498 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1499 // all indices for SequentialType elements. We must retain the same
1500 // semantic (zext) for unsigned types.
1501 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType())) {
1502 if (Ity->getBitWidth() < 64 && (*Indices)[i].S.isUnsigned()) {
1503 if (isa<Constant>(Index))
1504 Index = ConstantExpr::getCast(Instruction::ZExt,
1505 cast<Constant>(Index), Type::Int64Ty);
1507 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1508 makeNameUnique("gep"), CurBB);
1512 Result.push_back(Index);
1513 Ty = GetElementPtrInst::getIndexedType(PTy, Result.begin(),
1516 error("Index list invalid for constant getelementptr");
1521 unsigned upgradeCallingConv(unsigned CC) {
1523 case OldCallingConv::C : return CallingConv::C;
1524 case OldCallingConv::CSRet : return CallingConv::C;
1525 case OldCallingConv::Fast : return CallingConv::Fast;
1526 case OldCallingConv::Cold : return CallingConv::Cold;
1527 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1528 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1534 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1535 bool debug, bool addAttrs)
1538 CurFilename = infile;
1541 AddAttributes = addAttrs;
1542 ObsoleteVarArgs = false;
1545 CurModule.CurrentModule = new Module(CurFilename);
1547 // Check to make sure the parser succeeded
1550 delete ParserResult;
1551 std::cerr << "llvm-upgrade: parse failed.\n";
1555 // Check to make sure that parsing produced a result
1556 if (!ParserResult) {
1557 std::cerr << "llvm-upgrade: no parse result.\n";
1561 // Reset ParserResult variable while saving its value for the result.
1562 Module *Result = ParserResult;
1565 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1568 if ((F = Result->getFunction("llvm.va_start"))
1569 && F->getFunctionType()->getNumParams() == 0)
1570 ObsoleteVarArgs = true;
1571 if((F = Result->getFunction("llvm.va_copy"))
1572 && F->getFunctionType()->getNumParams() == 1)
1573 ObsoleteVarArgs = true;
1576 if (ObsoleteVarArgs && NewVarArgs) {
1577 error("This file is corrupt: it uses both new and old style varargs");
1581 if(ObsoleteVarArgs) {
1582 if(Function* F = Result->getFunction("llvm.va_start")) {
1583 if (F->arg_size() != 0) {
1584 error("Obsolete va_start takes 0 argument");
1590 //bar = alloca typeof(foo)
1594 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1595 const Type* ArgTy = F->getFunctionType()->getReturnType();
1596 const Type* ArgTyPtr = PointerType::getUnqual(ArgTy);
1597 Function* NF = cast<Function>(Result->getOrInsertFunction(
1598 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1600 while (!F->use_empty()) {
1601 CallInst* CI = cast<CallInst>(F->use_back());
1602 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1603 new CallInst(NF, bar, "", CI);
1604 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1605 CI->replaceAllUsesWith(foo);
1606 CI->getParent()->getInstList().erase(CI);
1608 Result->getFunctionList().erase(F);
1611 if(Function* F = Result->getFunction("llvm.va_end")) {
1612 if(F->arg_size() != 1) {
1613 error("Obsolete va_end takes 1 argument");
1619 //bar = alloca 1 of typeof(foo)
1621 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1622 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1623 const Type* ArgTyPtr = PointerType::getUnqual(ArgTy);
1624 Function* NF = cast<Function>(Result->getOrInsertFunction(
1625 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1627 while (!F->use_empty()) {
1628 CallInst* CI = cast<CallInst>(F->use_back());
1629 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1630 new StoreInst(CI->getOperand(1), bar, CI);
1631 new CallInst(NF, bar, "", CI);
1632 CI->getParent()->getInstList().erase(CI);
1634 Result->getFunctionList().erase(F);
1637 if(Function* F = Result->getFunction("llvm.va_copy")) {
1638 if(F->arg_size() != 1) {
1639 error("Obsolete va_copy takes 1 argument");
1644 //a = alloca 1 of typeof(foo)
1645 //b = alloca 1 of typeof(foo)
1650 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1651 const Type* ArgTy = F->getFunctionType()->getReturnType();
1652 const Type* ArgTyPtr = PointerType::getUnqual(ArgTy);
1653 Function* NF = cast<Function>(Result->getOrInsertFunction(
1654 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1656 while (!F->use_empty()) {
1657 CallInst* CI = cast<CallInst>(F->use_back());
1659 new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI),
1660 new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI)
1662 new StoreInst(CI->getOperand(1), Args[1], CI);
1663 new CallInst(NF, Args, Args + 2, "", CI);
1664 Value* foo = new LoadInst(Args[0], "vacopy.fix.3", CI);
1665 CI->replaceAllUsesWith(foo);
1666 CI->getParent()->getInstList().erase(CI);
1668 Result->getFunctionList().erase(F);
1675 } // end llvm namespace
1677 using namespace llvm;
1682 llvm::Module *ModuleVal;
1683 llvm::Function *FunctionVal;
1684 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1685 llvm::BasicBlock *BasicBlockVal;
1686 llvm::TermInstInfo TermInstVal;
1687 llvm::InstrInfo InstVal;
1688 llvm::ConstInfo ConstVal;
1689 llvm::ValueInfo ValueVal;
1690 llvm::PATypeInfo TypeVal;
1691 llvm::TypeInfo PrimType;
1692 llvm::PHIListInfo PHIList;
1693 std::list<llvm::PATypeInfo> *TypeList;
1694 std::vector<llvm::ValueInfo> *ValueList;
1695 std::vector<llvm::ConstInfo> *ConstVector;
1698 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1699 // Represent the RHS of PHI node
1700 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1702 llvm::GlobalValue::LinkageTypes Linkage;
1707 llvm::APFloat *FPVal;
1710 char *StrVal; // This memory is strdup'd!
1711 llvm::ValID ValIDVal; // strdup'd memory maybe!
1713 llvm::BinaryOps BinaryOpVal;
1714 llvm::TermOps TermOpVal;
1715 llvm::MemoryOps MemOpVal;
1716 llvm::OtherOps OtherOpVal;
1717 llvm::CastOps CastOpVal;
1718 llvm::ICmpInst::Predicate IPred;
1719 llvm::FCmpInst::Predicate FPred;
1720 llvm::Module::Endianness Endianness;
1723 %type <ModuleVal> Module FunctionList
1724 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1725 %type <BasicBlockVal> BasicBlock InstructionList
1726 %type <TermInstVal> BBTerminatorInst
1727 %type <InstVal> Inst InstVal MemoryInst
1728 %type <ConstVal> ConstVal ConstExpr
1729 %type <ConstVector> ConstVector
1730 %type <ArgList> ArgList ArgListH
1731 %type <ArgVal> ArgVal
1732 %type <PHIList> PHIList
1733 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1734 %type <ValueList> IndexList // For GEP derived indices
1735 %type <TypeList> TypeListI ArgTypeListI
1736 %type <JumpTable> JumpTable
1737 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1738 %type <BoolVal> OptVolatile // 'volatile' or not
1739 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1740 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1741 %type <Linkage> OptLinkage FnDeclareLinkage
1742 %type <Endianness> BigOrLittle
1744 // ValueRef - Unresolved reference to a definition or BB
1745 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1746 %type <ValueVal> ResolvedVal // <type> <valref> pair
1748 // Tokens and types for handling constant integer values
1750 // ESINT64VAL - A negative number within long long range
1751 %token <SInt64Val> ESINT64VAL
1753 // EUINT64VAL - A positive number within uns. long long range
1754 %token <UInt64Val> EUINT64VAL
1755 %type <SInt64Val> EINT64VAL
1757 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1758 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1759 %type <SIntVal> INTVAL
1760 %token <FPVal> FPVAL // Float or Double constant
1762 // Built in types...
1763 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1764 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1765 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1766 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1768 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1769 %type <StrVal> Name OptName OptAssign
1770 %type <UIntVal> OptAlign OptCAlign
1771 %type <StrVal> OptSection SectionString
1773 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1774 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1775 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1776 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1777 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1778 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1779 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1780 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1782 %type <UIntVal> OptCallingConv
1784 // Basic Block Terminating Operators
1785 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1786 %token UNWIND EXCEPT
1789 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1790 %type <BinaryOpVal> ShiftOps
1791 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1792 %token <BinaryOpVal> AND OR XOR SHL SHR ASHR LSHR
1793 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1794 %token <OtherOpVal> ICMP FCMP
1796 // Memory Instructions
1797 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1800 %token <OtherOpVal> PHI_TOK SELECT VAARG
1801 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1802 %token VAARG_old VANEXT_old //OBSOLETE
1804 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1805 %type <IPred> IPredicates
1806 %type <FPred> FPredicates
1807 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1808 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1810 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1811 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1812 %type <CastOpVal> CastOps
1818 // Handle constant integer size restriction and conversion...
1823 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1824 error("Value too large for type");
1830 : ESINT64VAL // These have same type and can't cause problems...
1832 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1833 error("Value too large for type");
1837 // Operations that are notably excluded from this list include:
1838 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1841 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1849 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1853 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1854 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1855 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1856 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1857 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1861 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1862 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1863 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1864 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1865 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1866 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1867 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1868 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1869 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1872 : SHL | SHR | ASHR | LSHR
1876 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1877 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1880 // These are some types that allow classification if we only want a particular
1881 // thing... for example, only a signed, unsigned, or integral type.
1883 : LONG | INT | SHORT | SBYTE
1887 : ULONG | UINT | USHORT | UBYTE
1891 : SIntType | UIntType
1898 // OptAssign - Value producing statements have an optional assignment component
1908 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1909 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1910 | WEAK { $$ = GlobalValue::WeakLinkage; }
1911 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1912 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1913 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1914 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1915 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1919 : /*empty*/ { $$ = lastCallingConv = OldCallingConv::C; }
1920 | CCC_TOK { $$ = lastCallingConv = OldCallingConv::C; }
1921 | CSRETCC_TOK { $$ = lastCallingConv = OldCallingConv::CSRet; }
1922 | FASTCC_TOK { $$ = lastCallingConv = OldCallingConv::Fast; }
1923 | COLDCC_TOK { $$ = lastCallingConv = OldCallingConv::Cold; }
1924 | X86_STDCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_StdCall; }
1925 | X86_FASTCALLCC_TOK { $$ = lastCallingConv = OldCallingConv::X86_FastCall; }
1926 | CC_TOK EUINT64VAL {
1927 if ((unsigned)$2 != $2)
1928 error("Calling conv too large");
1929 $$ = lastCallingConv = $2;
1933 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1934 // a comma before it.
1936 : /*empty*/ { $$ = 0; }
1937 | ALIGN EUINT64VAL {
1939 if ($$ != 0 && !isPowerOf2_32($$))
1940 error("Alignment must be a power of two");
1945 : /*empty*/ { $$ = 0; }
1946 | ',' ALIGN EUINT64VAL {
1948 if ($$ != 0 && !isPowerOf2_32($$))
1949 error("Alignment must be a power of two");
1954 : SECTION STRINGCONSTANT {
1955 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1956 if ($2[i] == '"' || $2[i] == '\\')
1957 error("Invalid character in section name");
1963 : /*empty*/ { $$ = 0; }
1964 | SectionString { $$ = $1; }
1967 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1968 // is set to be the global we are processing.
1972 | ',' GlobalVarAttribute GlobalVarAttributes {}
1977 CurGV->setSection($1);
1980 | ALIGN EUINT64VAL {
1981 if ($2 != 0 && !isPowerOf2_32($2))
1982 error("Alignment must be a power of two");
1983 CurGV->setAlignment($2);
1988 //===----------------------------------------------------------------------===//
1989 // Types includes all predefined types... except void, because it can only be
1990 // used in specific contexts (function returning void for example). To have
1991 // access to it, a user must explicitly use TypesV.
1994 // TypesV includes all of 'Types', but it also includes the void type.
1998 $$.PAT = new PATypeHolder($1.T);
1999 $$.S.makeSignless();
2006 $$.PAT = new PATypeHolder($1.T);
2007 $$.S.makeSignless();
2013 if (!UpRefs.empty())
2014 error("Invalid upreference in type: " + (*$1.PAT)->getDescription());
2020 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
2021 | LONG | ULONG | FLOAT | DOUBLE | LABEL
2024 // Derived types are added later...
2027 $$.PAT = new PATypeHolder($1.T);
2031 $$.PAT = new PATypeHolder(OpaqueType::get());
2032 $$.S.makeSignless();
2034 | SymbolicValueRef { // Named types are also simple types...
2035 $$.S.copy(getTypeSign($1));
2036 const Type* tmp = getType($1);
2037 $$.PAT = new PATypeHolder(tmp);
2039 | '\\' EUINT64VAL { // Type UpReference
2040 if ($2 > (uint64_t)~0U)
2041 error("Value out of range");
2042 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
2043 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
2044 $$.PAT = new PATypeHolder(OT);
2045 $$.S.makeSignless();
2046 UR_OUT("New Upreference!\n");
2048 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
2049 $$.S.makeComposite($1.S);
2050 std::vector<const Type*> Params;
2051 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2052 E = $3->end(); I != E; ++I) {
2053 Params.push_back(I->PAT->get());
2056 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
2057 if (isVarArg) Params.pop_back();
2059 const ParamAttrsList *PAL = 0;
2060 if (lastCallingConv == OldCallingConv::CSRet) {
2061 ParamAttrsVector Attrs;
2062 ParamAttrsWithIndex PAWI;
2063 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
2064 Attrs.push_back(PAWI);
2065 PAL = ParamAttrsList::get(Attrs);
2068 const FunctionType *FTy =
2069 FunctionType::get($1.PAT->get(), Params, isVarArg);
2071 $$.PAT = new PATypeHolder( HandleUpRefs(FTy, $$.S) );
2072 delete $1.PAT; // Delete the return type handle
2073 delete $3; // Delete the argument list
2075 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
2076 $$.S.makeComposite($4.S);
2077 $$.PAT = new PATypeHolder(HandleUpRefs(ArrayType::get($4.PAT->get(),
2078 (unsigned)$2), $$.S));
2081 | '<' EUINT64VAL 'x' UpRTypes '>' { // Vector type?
2082 const llvm::Type* ElemTy = $4.PAT->get();
2083 if ((unsigned)$2 != $2)
2084 error("Unsigned result not equal to signed result");
2085 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
2086 error("Elements of a VectorType must be integer or floating point");
2087 if (!isPowerOf2_32($2))
2088 error("VectorType length should be a power of 2");
2089 $$.S.makeComposite($4.S);
2090 $$.PAT = new PATypeHolder(HandleUpRefs(VectorType::get(ElemTy,
2091 (unsigned)$2), $$.S));
2094 | '{' TypeListI '}' { // Structure type?
2095 std::vector<const Type*> Elements;
2096 $$.S.makeComposite();
2097 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
2098 E = $2->end(); I != E; ++I) {
2099 Elements.push_back(I->PAT->get());
2102 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements), $$.S));
2105 | '{' '}' { // Empty structure type?
2106 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>()));
2107 $$.S.makeComposite();
2109 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
2110 $$.S.makeComposite();
2111 std::vector<const Type*> Elements;
2112 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
2113 E = $3->end(); I != E; ++I) {
2114 Elements.push_back(I->PAT->get());
2118 $$.PAT = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true),
2122 | '<' '{' '}' '>' { // Empty packed structure type?
2123 $$.PAT = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
2124 $$.S.makeComposite();
2126 | UpRTypes '*' { // Pointer type?
2127 if ($1.PAT->get() == Type::LabelTy)
2128 error("Cannot form a pointer to a basic block");
2129 $$.S.makeComposite($1.S);
2131 PATypeHolder(HandleUpRefs(PointerType::getUnqual($1.PAT->get()),
2137 // TypeList - Used for struct declarations and as a basis for function type
2138 // declaration type lists
2142 $$ = new std::list<PATypeInfo>();
2145 | TypeListI ',' UpRTypes {
2146 ($$=$1)->push_back($3);
2150 // ArgTypeList - List of types for a function type declaration...
2153 | TypeListI ',' DOTDOTDOT {
2155 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2156 VoidTI.S.makeSignless();
2157 ($$=$1)->push_back(VoidTI);
2160 $$ = new std::list<PATypeInfo>();
2162 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2163 VoidTI.S.makeSignless();
2164 $$->push_back(VoidTI);
2167 $$ = new std::list<PATypeInfo>();
2171 // ConstVal - The various declarations that go into the constant pool. This
2172 // production is used ONLY to represent constants that show up AFTER a 'const',
2173 // 'constant' or 'global' token at global scope. Constants that can be inlined
2174 // into other expressions (such as integers and constexprs) are handled by the
2175 // ResolvedVal, ValueRef and ConstValueRef productions.
2178 : Types '[' ConstVector ']' { // Nonempty unsized arr
2179 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2181 error("Cannot make array constant with type: '" +
2182 $1.PAT->get()->getDescription() + "'");
2183 const Type *ETy = ATy->getElementType();
2184 int NumElements = ATy->getNumElements();
2186 // Verify that we have the correct size...
2187 if (NumElements != -1 && NumElements != (int)$3->size())
2188 error("Type mismatch: constant sized array initialized with " +
2189 utostr($3->size()) + " arguments, but has size of " +
2190 itostr(NumElements) + "");
2192 // Verify all elements are correct type!
2193 std::vector<Constant*> Elems;
2194 for (unsigned i = 0; i < $3->size(); i++) {
2195 Constant *C = (*$3)[i].C;
2196 const Type* ValTy = C->getType();
2198 error("Element #" + utostr(i) + " is not of type '" +
2199 ETy->getDescription() +"' as required!\nIt is of type '"+
2200 ValTy->getDescription() + "'");
2203 $$.C = ConstantArray::get(ATy, Elems);
2209 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2211 error("Cannot make array constant with type: '" +
2212 $1.PAT->get()->getDescription() + "'");
2213 int NumElements = ATy->getNumElements();
2214 if (NumElements != -1 && NumElements != 0)
2215 error("Type mismatch: constant sized array initialized with 0"
2216 " arguments, but has size of " + itostr(NumElements) +"");
2217 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
2221 | Types 'c' STRINGCONSTANT {
2222 const ArrayType *ATy = dyn_cast<ArrayType>($1.PAT->get());
2224 error("Cannot make array constant with type: '" +
2225 $1.PAT->get()->getDescription() + "'");
2226 int NumElements = ATy->getNumElements();
2227 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
2228 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
2229 error("String arrays require type i8, not '" + ETy->getDescription() +
2231 char *EndStr = UnEscapeLexed($3, true);
2232 if (NumElements != -1 && NumElements != (EndStr-$3))
2233 error("Can't build string constant of size " +
2234 itostr((int)(EndStr-$3)) + " when array has size " +
2235 itostr(NumElements) + "");
2236 std::vector<Constant*> Vals;
2237 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
2238 Vals.push_back(ConstantInt::get(ETy, *C));
2240 $$.C = ConstantArray::get(ATy, Vals);
2244 | Types '<' ConstVector '>' { // Nonempty unsized arr
2245 const VectorType *PTy = dyn_cast<VectorType>($1.PAT->get());
2247 error("Cannot make packed constant with type: '" +
2248 $1.PAT->get()->getDescription() + "'");
2249 const Type *ETy = PTy->getElementType();
2250 int NumElements = PTy->getNumElements();
2251 // Verify that we have the correct size...
2252 if (NumElements != -1 && NumElements != (int)$3->size())
2253 error("Type mismatch: constant sized packed initialized with " +
2254 utostr($3->size()) + " arguments, but has size of " +
2255 itostr(NumElements) + "");
2256 // Verify all elements are correct type!
2257 std::vector<Constant*> Elems;
2258 for (unsigned i = 0; i < $3->size(); i++) {
2259 Constant *C = (*$3)[i].C;
2260 const Type* ValTy = C->getType();
2262 error("Element #" + utostr(i) + " is not of type '" +
2263 ETy->getDescription() +"' as required!\nIt is of type '"+
2264 ValTy->getDescription() + "'");
2267 $$.C = ConstantVector::get(PTy, Elems);
2272 | Types '{' ConstVector '}' {
2273 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2275 error("Cannot make struct constant with type: '" +
2276 $1.PAT->get()->getDescription() + "'");
2277 if ($3->size() != STy->getNumContainedTypes())
2278 error("Illegal number of initializers for structure type");
2280 // Check to ensure that constants are compatible with the type initializer!
2281 std::vector<Constant*> Fields;
2282 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
2283 Constant *C = (*$3)[i].C;
2284 if (C->getType() != STy->getElementType(i))
2285 error("Expected type '" + STy->getElementType(i)->getDescription() +
2286 "' for element #" + utostr(i) + " of structure initializer");
2287 Fields.push_back(C);
2289 $$.C = ConstantStruct::get(STy, Fields);
2295 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2297 error("Cannot make struct constant with type: '" +
2298 $1.PAT->get()->getDescription() + "'");
2299 if (STy->getNumContainedTypes() != 0)
2300 error("Illegal number of initializers for structure type");
2301 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2305 | Types '<' '{' ConstVector '}' '>' {
2306 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2308 error("Cannot make packed struct constant with type: '" +
2309 $1.PAT->get()->getDescription() + "'");
2310 if ($4->size() != STy->getNumContainedTypes())
2311 error("Illegal number of initializers for packed structure type");
2313 // Check to ensure that constants are compatible with the type initializer!
2314 std::vector<Constant*> Fields;
2315 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2316 Constant *C = (*$4)[i].C;
2317 if (C->getType() != STy->getElementType(i))
2318 error("Expected type '" + STy->getElementType(i)->getDescription() +
2319 "' for element #" + utostr(i) + " of packed struct initializer");
2320 Fields.push_back(C);
2322 $$.C = ConstantStruct::get(STy, Fields);
2327 | Types '<' '{' '}' '>' {
2328 const StructType *STy = dyn_cast<StructType>($1.PAT->get());
2330 error("Cannot make packed struct constant with type: '" +
2331 $1.PAT->get()->getDescription() + "'");
2332 if (STy->getNumContainedTypes() != 0)
2333 error("Illegal number of initializers for packed structure type");
2334 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2339 const PointerType *PTy = dyn_cast<PointerType>($1.PAT->get());
2341 error("Cannot make null pointer constant with type: '" +
2342 $1.PAT->get()->getDescription() + "'");
2343 $$.C = ConstantPointerNull::get(PTy);
2348 $$.C = UndefValue::get($1.PAT->get());
2352 | Types SymbolicValueRef {
2353 const PointerType *Ty = dyn_cast<PointerType>($1.PAT->get());
2355 error("Global const reference must be a pointer type, not" +
2356 $1.PAT->get()->getDescription());
2358 // ConstExprs can exist in the body of a function, thus creating
2359 // GlobalValues whenever they refer to a variable. Because we are in
2360 // the context of a function, getExistingValue will search the functions
2361 // symbol table instead of the module symbol table for the global symbol,
2362 // which throws things all off. To get around this, we just tell
2363 // getExistingValue that we are at global scope here.
2365 Function *SavedCurFn = CurFun.CurrentFunction;
2366 CurFun.CurrentFunction = 0;
2368 Value *V = getExistingValue(Ty, $2);
2369 CurFun.CurrentFunction = SavedCurFn;
2371 // If this is an initializer for a constant pointer, which is referencing a
2372 // (currently) undefined variable, create a stub now that shall be replaced
2373 // in the future with the right type of variable.
2376 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2377 const PointerType *PT = cast<PointerType>(Ty);
2379 // First check to see if the forward references value is already created!
2380 PerModuleInfo::GlobalRefsType::iterator I =
2381 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2383 if (I != CurModule.GlobalRefs.end()) {
2384 V = I->second; // Placeholder already exists, use it...
2388 if ($2.Type == ValID::NameVal) Name = $2.Name;
2390 // Create the forward referenced global.
2392 if (const FunctionType *FTy =
2393 dyn_cast<FunctionType>(PT->getElementType())) {
2394 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2395 CurModule.CurrentModule);
2397 GV = new GlobalVariable(PT->getElementType(), false,
2398 GlobalValue::ExternalLinkage, 0,
2399 Name, CurModule.CurrentModule);
2402 // Keep track of the fact that we have a forward ref to recycle it
2403 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2407 $$.C = cast<GlobalValue>(V);
2409 delete $1.PAT; // Free the type handle
2412 if ($1.PAT->get() != $2.C->getType())
2413 error("Mismatched types for constant expression");
2418 | Types ZEROINITIALIZER {
2419 const Type *Ty = $1.PAT->get();
2420 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2421 error("Cannot create a null initialized value of this type");
2422 $$.C = Constant::getNullValue(Ty);
2426 | SIntType EINT64VAL { // integral constants
2427 const Type *Ty = $1.T;
2428 if (!ConstantInt::isValueValidForType(Ty, $2))
2429 error("Constant value doesn't fit in type");
2430 $$.C = ConstantInt::get(Ty, $2);
2433 | UIntType EUINT64VAL { // integral constants
2434 const Type *Ty = $1.T;
2435 if (!ConstantInt::isValueValidForType(Ty, $2))
2436 error("Constant value doesn't fit in type");
2437 $$.C = ConstantInt::get(Ty, $2);
2438 $$.S.makeUnsigned();
2440 | BOOL TRUETOK { // Boolean constants
2441 $$.C = ConstantInt::get(Type::Int1Ty, true);
2442 $$.S.makeUnsigned();
2444 | BOOL FALSETOK { // Boolean constants
2445 $$.C = ConstantInt::get(Type::Int1Ty, false);
2446 $$.S.makeUnsigned();
2448 | FPType FPVAL { // Float & Double constants
2449 if (!ConstantFP::isValueValidForType($1.T, *$2))
2450 error("Floating point constant invalid for type");
2451 // Lexer has no type info, so builds all FP constants as double.
2453 if ($1.T==Type::FloatTy)
2454 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
2455 $$.C = ConstantFP::get($1.T, *$2);
2457 $$.S.makeSignless();
2462 : CastOps '(' ConstVal TO Types ')' {
2463 const Type* SrcTy = $3.C->getType();
2464 const Type* DstTy = $5.PAT->get();
2465 Signedness SrcSign($3.S);
2466 Signedness DstSign($5.S);
2467 if (!SrcTy->isFirstClassType())
2468 error("cast constant expression from a non-primitive type: '" +
2469 SrcTy->getDescription() + "'");
2470 if (!DstTy->isFirstClassType())
2471 error("cast constant expression to a non-primitive type: '" +
2472 DstTy->getDescription() + "'");
2473 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2477 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2478 const Type *Ty = $3.C->getType();
2479 if (!isa<PointerType>(Ty))
2480 error("GetElementPtr requires a pointer operand");
2482 std::vector<Constant*> CIndices;
2483 upgradeGEPCEIndices($3.C->getType(), $4, CIndices);
2486 $$.C = ConstantExpr::getGetElementPtr($3.C, &CIndices[0], CIndices.size());
2487 $$.S.copy(getElementSign($3, CIndices));
2489 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2490 if (!$3.C->getType()->isInteger() ||
2491 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2492 error("Select condition must be bool type");
2493 if ($5.C->getType() != $7.C->getType())
2494 error("Select operand types must match");
2495 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2498 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2499 const Type *Ty = $3.C->getType();
2500 if (Ty != $5.C->getType())
2501 error("Binary operator types must match");
2502 // First, make sure we're dealing with the right opcode by upgrading from
2503 // obsolete versions.
2504 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2506 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2507 // To retain backward compatibility with these early compilers, we emit a
2508 // cast to the appropriate integer type automatically if we are in the
2509 // broken case. See PR424 for more information.
2510 if (!isa<PointerType>(Ty)) {
2511 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2513 const Type *IntPtrTy = 0;
2514 switch (CurModule.CurrentModule->getPointerSize()) {
2515 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2516 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2517 default: error("invalid pointer binary constant expr");
2519 $$.C = ConstantExpr::get(Opcode,
2520 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2521 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2522 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2526 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2527 const Type* Ty = $3.C->getType();
2528 if (Ty != $5.C->getType())
2529 error("Logical operator types must match");
2530 if (!Ty->isInteger()) {
2531 if (!isa<VectorType>(Ty) ||
2532 !cast<VectorType>(Ty)->getElementType()->isInteger())
2533 error("Logical operator requires integer operands");
2535 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2536 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2539 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2540 const Type* Ty = $3.C->getType();
2541 if (Ty != $5.C->getType())
2542 error("setcc operand types must match");
2543 unsigned short pred;
2544 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2545 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2546 $$.S.makeUnsigned();
2548 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2549 if ($4.C->getType() != $6.C->getType())
2550 error("icmp operand types must match");
2551 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2552 $$.S.makeUnsigned();
2554 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2555 if ($4.C->getType() != $6.C->getType())
2556 error("fcmp operand types must match");
2557 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2558 $$.S.makeUnsigned();
2560 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2561 if (!$5.C->getType()->isInteger() ||
2562 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2563 error("Shift count for shift constant must be unsigned byte");
2564 const Type* Ty = $3.C->getType();
2565 if (!$3.C->getType()->isInteger())
2566 error("Shift constant expression requires integer operand");
2567 Constant *ShiftAmt = ConstantExpr::getZExt($5.C, Ty);
2568 $$.C = ConstantExpr::get(getBinaryOp($1, Ty, $3.S), $3.C, ShiftAmt);
2571 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2572 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2573 error("Invalid extractelement operands");
2574 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2575 $$.S.copy($3.S.get(0));
2577 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2578 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2579 error("Invalid insertelement operands");
2580 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2583 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2584 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2585 error("Invalid shufflevector operands");
2586 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2592 // ConstVector - A list of comma separated constants.
2594 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2596 $$ = new std::vector<ConstInfo>();
2602 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2604 : GLOBAL { $$ = false; }
2605 | CONSTANT { $$ = true; }
2609 //===----------------------------------------------------------------------===//
2610 // Rules to match Modules
2611 //===----------------------------------------------------------------------===//
2613 // Module rule: Capture the result of parsing the whole file into a result
2618 $$ = ParserResult = $1;
2619 CurModule.ModuleDone();
2623 // FunctionList - A list of functions, preceeded by a constant pool.
2626 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2627 | FunctionList FunctionProto { $$ = $1; }
2628 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2629 | FunctionList IMPLEMENTATION { $$ = $1; }
2631 $$ = CurModule.CurrentModule;
2632 // Emit an error if there are any unresolved types left.
2633 if (!CurModule.LateResolveTypes.empty()) {
2634 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2635 if (DID.Type == ValID::NameVal) {
2636 error("Reference to an undefined type: '"+DID.getName() + "'");
2638 error("Reference to an undefined type: #" + itostr(DID.Num));
2644 // ConstPool - Constants with optional names assigned to them.
2646 : ConstPool OptAssign TYPE TypesV {
2647 // Eagerly resolve types. This is not an optimization, this is a
2648 // requirement that is due to the fact that we could have this:
2650 // %list = type { %list * }
2651 // %list = type { %list * } ; repeated type decl
2653 // If types are not resolved eagerly, then the two types will not be
2654 // determined to be the same type!
2656 ResolveTypeTo($2, $4.PAT->get(), $4.S);
2658 if (!setTypeName($4, $2) && !$2) {
2659 // If this is a numbered type that is not a redefinition, add it to the
2661 CurModule.Types.push_back($4.PAT->get());
2662 CurModule.TypeSigns.push_back($4.S);
2666 | ConstPool FunctionProto { // Function prototypes can be in const pool
2668 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2670 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2672 error("Global value initializer is not a constant");
2673 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C, $5.S);
2674 } GlobalVarAttributes {
2677 | ConstPool OptAssign EXTERNAL GlobalType Types {
2678 const Type *Ty = $5.PAT->get();
2679 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0,
2682 } GlobalVarAttributes {
2685 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2686 const Type *Ty = $5.PAT->get();
2687 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0,
2690 } GlobalVarAttributes {
2693 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2694 const Type *Ty = $5.PAT->get();
2696 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0,
2699 } GlobalVarAttributes {
2702 | ConstPool TARGET TargetDefinition {
2704 | ConstPool DEPLIBS '=' LibrariesDefinition {
2706 | /* empty: end of list */ {
2712 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2713 char *EndStr = UnEscapeLexed($1, true);
2714 std::string NewAsm($1, EndStr);
2717 if (AsmSoFar.empty())
2718 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2720 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2725 : BIG { $$ = Module::BigEndian; }
2726 | LITTLE { $$ = Module::LittleEndian; }
2730 : ENDIAN '=' BigOrLittle {
2731 CurModule.setEndianness($3);
2733 | POINTERSIZE '=' EUINT64VAL {
2735 CurModule.setPointerSize(Module::Pointer32);
2737 CurModule.setPointerSize(Module::Pointer64);
2739 error("Invalid pointer size: '" + utostr($3) + "'");
2741 | TRIPLE '=' STRINGCONSTANT {
2742 CurModule.CurrentModule->setTargetTriple($3);
2745 | DATALAYOUT '=' STRINGCONSTANT {
2746 CurModule.CurrentModule->setDataLayout($3);
2756 : LibList ',' STRINGCONSTANT {
2757 CurModule.CurrentModule->addLibrary($3);
2761 CurModule.CurrentModule->addLibrary($1);
2764 | /* empty: end of list */ { }
2767 //===----------------------------------------------------------------------===//
2768 // Rules to match Function Headers
2769 //===----------------------------------------------------------------------===//
2772 : VAR_ID | STRINGCONSTANT
2777 | /*empty*/ { $$ = 0; }
2782 if ($1.PAT->get() == Type::VoidTy)
2783 error("void typed arguments are invalid");
2784 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2789 : ArgListH ',' ArgVal {
2795 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2802 : ArgListH { $$ = $1; }
2803 | ArgListH ',' DOTDOTDOT {
2806 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2807 VoidTI.S.makeSignless();
2808 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2811 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2813 VoidTI.PAT = new PATypeHolder(Type::VoidTy);
2814 VoidTI.S.makeSignless();
2815 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2817 | /* empty */ { $$ = 0; }
2821 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2823 std::string FunctionName($3);
2824 free($3); // Free strdup'd memory!
2826 const Type* RetTy = $2.PAT->get();
2828 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2829 error("LLVM functions cannot return aggregate types");
2832 FTySign.makeComposite($2.S);
2833 std::vector<const Type*> ParamTyList;
2835 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2836 // i8*. We check here for those names and override the parameter list
2837 // types to ensure the prototype is correct.
2838 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2839 ParamTyList.push_back(PointerType::getUnqual(Type::Int8Ty));
2840 } else if (FunctionName == "llvm.va_copy") {
2841 ParamTyList.push_back(PointerType::getUnqual(Type::Int8Ty));
2842 ParamTyList.push_back(PointerType::getUnqual(Type::Int8Ty));
2843 } else if ($5) { // If there are arguments...
2844 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2845 I = $5->begin(), E = $5->end(); I != E; ++I) {
2846 const Type *Ty = I->first.PAT->get();
2847 ParamTyList.push_back(Ty);
2848 FTySign.add(I->first.S);
2852 bool isVarArg = ParamTyList.size() && ParamTyList.back() == Type::VoidTy;
2854 ParamTyList.pop_back();
2856 const FunctionType *FT = FunctionType::get(RetTy, ParamTyList, isVarArg);
2857 const PointerType *PFT = PointerType::getUnqual(FT);
2861 if (!FunctionName.empty()) {
2862 ID = ValID::create((char*)FunctionName.c_str());
2864 ID = ValID::create((int)CurModule.Values[PFT].size());
2866 ID.S.makeComposite(FTySign);
2869 Module* M = CurModule.CurrentModule;
2871 // See if this function was forward referenced. If so, recycle the object.
2872 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2873 // Move the function to the end of the list, from whereever it was
2874 // previously inserted.
2875 Fn = cast<Function>(FWRef);
2876 M->getFunctionList().remove(Fn);
2877 M->getFunctionList().push_back(Fn);
2878 } else if (!FunctionName.empty()) {
2879 GlobalValue *Conflict = M->getFunction(FunctionName);
2881 Conflict = M->getNamedGlobal(FunctionName);
2882 if (Conflict && PFT == Conflict->getType()) {
2883 if (!CurFun.isDeclare && !Conflict->isDeclaration()) {
2884 // We have two function definitions that conflict, same type, same
2885 // name. We should really check to make sure that this is the result
2886 // of integer type planes collapsing and generate an error if it is
2887 // not, but we'll just rename on the assumption that it is. However,
2888 // let's do it intelligently and rename the internal linkage one
2890 std::string NewName(makeNameUnique(FunctionName));
2891 if (Conflict->hasInternalLinkage()) {
2892 Conflict->setName(NewName);
2894 makeRenameMapKey(FunctionName, Conflict->getType(), ID.S);
2895 CurModule.RenameMap[Key] = NewName;
2896 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2897 InsertValue(Fn, CurModule.Values);
2899 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2900 InsertValue(Fn, CurModule.Values);
2902 makeRenameMapKey(FunctionName, PFT, ID.S);
2903 CurModule.RenameMap[Key] = NewName;
2906 // If they are not both definitions, then just use the function we
2907 // found since the types are the same.
2908 Fn = cast<Function>(Conflict);
2910 // Make sure to strip off any argument names so we can't get
2912 if (Fn->isDeclaration())
2913 for (Function::arg_iterator AI = Fn->arg_begin(),
2914 AE = Fn->arg_end(); AI != AE; ++AI)
2917 } else if (Conflict) {
2918 // We have two globals with the same name and different types.
2919 // Previously, this was permitted because the symbol table had
2920 // "type planes" and names only needed to be distinct within a
2921 // type plane. After PR411 was fixed, this is no loner the case.
2922 // To resolve this we must rename one of the two.
2923 if (Conflict->hasInternalLinkage()) {
2924 // We can safely rename the Conflict.
2926 makeRenameMapKey(Conflict->getName(), Conflict->getType(),
2927 CurModule.NamedValueSigns[Conflict->getName()]);
2928 Conflict->setName(makeNameUnique(Conflict->getName()));
2929 CurModule.RenameMap[Key] = Conflict->getName();
2930 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2931 InsertValue(Fn, CurModule.Values);
2933 // We can't quietly rename either of these things, but we must
2934 // rename one of them. Only if the function's linkage is internal can
2935 // we forgo a warning message about the renamed function.
2936 std::string NewName = makeNameUnique(FunctionName);
2937 if (CurFun.Linkage != GlobalValue::InternalLinkage) {
2938 warning("Renaming function '" + FunctionName + "' as '" + NewName +
2939 "' may cause linkage errors");
2941 // Elect to rename the thing we're now defining.
2942 Fn = new Function(FT, CurFun.Linkage, NewName, M);
2943 InsertValue(Fn, CurModule.Values);
2944 RenameMapKey Key = makeRenameMapKey(FunctionName, PFT, ID.S);
2945 CurModule.RenameMap[Key] = NewName;
2948 // There's no conflict, just define the function
2949 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2950 InsertValue(Fn, CurModule.Values);
2953 // There's no conflict, just define the function
2954 Fn = new Function(FT, CurFun.Linkage, FunctionName, M);
2955 InsertValue(Fn, CurModule.Values);
2959 CurFun.FunctionStart(Fn);
2961 if (CurFun.isDeclare) {
2962 // If we have declaration, always overwrite linkage. This will allow us
2963 // to correctly handle cases, when pointer to function is passed as
2964 // argument to another function.
2965 Fn->setLinkage(CurFun.Linkage);
2967 Fn->setCallingConv(upgradeCallingConv($1));
2968 Fn->setAlignment($8);
2974 // Convert the CSRet calling convention into the corresponding parameter
2976 if ($1 == OldCallingConv::CSRet) {
2977 ParamAttrsVector Attrs;
2978 ParamAttrsWithIndex PAWI;
2979 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
2980 Attrs.push_back(PAWI);
2981 Fn->setParamAttrs(ParamAttrsList::get(Attrs));
2984 // Add all of the arguments we parsed to the function...
2985 if ($5) { // Is null if empty...
2986 if (isVarArg) { // Nuke the last entry
2987 assert($5->back().first.PAT->get() == Type::VoidTy &&
2988 $5->back().second == 0 && "Not a varargs marker");
2989 delete $5->back().first.PAT;
2990 $5->pop_back(); // Delete the last entry
2992 Function::arg_iterator ArgIt = Fn->arg_begin();
2993 Function::arg_iterator ArgEnd = Fn->arg_end();
2994 std::vector<std::pair<PATypeInfo,char*> >::iterator I = $5->begin();
2995 std::vector<std::pair<PATypeInfo,char*> >::iterator E = $5->end();
2996 for ( ; I != E && ArgIt != ArgEnd; ++I, ++ArgIt) {
2997 delete I->first.PAT; // Delete the typeholder...
2998 ValueInfo VI; VI.V = ArgIt; VI.S.copy(I->first.S);
2999 setValueName(VI, I->second); // Insert arg into symtab...
3002 delete $5; // We're now done with the argument list
3004 lastCallingConv = OldCallingConv::C;
3009 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
3013 : OptLinkage { CurFun.Linkage = $1; } FunctionHeaderH BEGIN {
3014 $$ = CurFun.CurrentFunction;
3016 // Make sure that we keep track of the linkage type even if there was a
3017 // previous "declare".
3023 : ENDTOK | '}' // Allow end of '}' to end a function
3027 : BasicBlockList END {
3032 : /*default*/ { $$ = GlobalValue::ExternalLinkage; }
3033 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
3034 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
3038 : DECLARE { CurFun.isDeclare = true; }
3039 FnDeclareLinkage { CurFun.Linkage = $3; } FunctionHeaderH {
3040 $$ = CurFun.CurrentFunction;
3041 CurFun.FunctionDone();
3046 //===----------------------------------------------------------------------===//
3047 // Rules to match Basic Blocks
3048 //===----------------------------------------------------------------------===//
3051 : /* empty */ { $$ = false; }
3052 | SIDEEFFECT { $$ = true; }
3056 // A reference to a direct constant
3057 : ESINT64VAL { $$ = ValID::create($1); }
3058 | EUINT64VAL { $$ = ValID::create($1); }
3059 | FPVAL { $$ = ValID::create($1); }
3061 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true));
3062 $$.S.makeUnsigned();
3065 $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false));
3066 $$.S.makeUnsigned();
3068 | NULL_TOK { $$ = ValID::createNull(); }
3069 | UNDEF { $$ = ValID::createUndef(); }
3070 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
3071 | '<' ConstVector '>' { // Nonempty unsized packed vector
3072 const Type *ETy = (*$2)[0].C->getType();
3073 int NumElements = $2->size();
3074 VectorType* pt = VectorType::get(ETy, NumElements);
3075 $$.S.makeComposite((*$2)[0].S);
3076 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt, $$.S));
3078 // Verify all elements are correct type!
3079 std::vector<Constant*> Elems;
3080 for (unsigned i = 0; i < $2->size(); i++) {
3081 Constant *C = (*$2)[i].C;
3082 const Type *CTy = C->getType();
3084 error("Element #" + utostr(i) + " is not of type '" +
3085 ETy->getDescription() +"' as required!\nIt is of type '" +
3086 CTy->getDescription() + "'");
3089 $$ = ValID::create(ConstantVector::get(pt, Elems));
3090 delete PTy; delete $2;
3093 $$ = ValID::create($1.C);
3096 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
3097 char *End = UnEscapeLexed($3, true);
3098 std::string AsmStr = std::string($3, End);
3099 End = UnEscapeLexed($5, true);
3100 std::string Constraints = std::string($5, End);
3101 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
3107 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
3111 : INTVAL { $$ = ValID::create($1); $$.S.makeSignless(); }
3112 | Name { $$ = ValID::create($1); $$.S.makeSignless(); }
3115 // ValueRef - A reference to a definition... either constant or symbolic
3117 : SymbolicValueRef | ConstValueRef
3121 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
3122 // type immediately preceeds the value reference, and allows complex constant
3123 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
3126 const Type *Ty = $1.PAT->get();
3128 $$.V = getVal(Ty, $2);
3135 : BasicBlockList BasicBlock {
3138 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
3143 // Basic blocks are terminated by branching instructions:
3144 // br, br/cc, switch, ret
3147 : InstructionList OptAssign BBTerminatorInst {
3148 ValueInfo VI; VI.V = $3.TI; VI.S.copy($3.S);
3149 setValueName(VI, $2);
3151 $1->getInstList().push_back($3.TI);
3158 : InstructionList Inst {
3160 $1->getInstList().push_back($2.I);
3164 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++),true);
3165 // Make sure to move the basic block to the correct location in the
3166 // function, instead of leaving it inserted wherever it was first
3168 Function::BasicBlockListType &BBL =
3169 CurFun.CurrentFunction->getBasicBlockList();
3170 BBL.splice(BBL.end(), BBL, $$);
3173 $$ = CurBB = getBBVal(ValID::create($1), true);
3174 // Make sure to move the basic block to the correct location in the
3175 // function, instead of leaving it inserted wherever it was first
3177 Function::BasicBlockListType &BBL =
3178 CurFun.CurrentFunction->getBasicBlockList();
3179 BBL.splice(BBL.end(), BBL, $$);
3183 Unwind : UNWIND | EXCEPT;
3186 : RET ResolvedVal { // Return with a result...
3187 $$.TI = new ReturnInst($2.V);
3188 $$.S.makeSignless();
3190 | RET VOID { // Return with no result...
3191 $$.TI = new ReturnInst();
3192 $$.S.makeSignless();
3194 | BR LABEL ValueRef { // Unconditional Branch...
3195 BasicBlock* tmpBB = getBBVal($3);
3196 $$.TI = new BranchInst(tmpBB);
3197 $$.S.makeSignless();
3198 } // Conditional Branch...
3199 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
3200 $6.S.makeSignless();
3201 $9.S.makeSignless();
3202 BasicBlock* tmpBBA = getBBVal($6);
3203 BasicBlock* tmpBBB = getBBVal($9);
3204 $3.S.makeUnsigned();
3205 Value* tmpVal = getVal(Type::Int1Ty, $3);
3206 $$.TI = new BranchInst(tmpBBA, tmpBBB, tmpVal);
3207 $$.S.makeSignless();
3209 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
3211 Value* tmpVal = getVal($2.T, $3);
3212 $6.S.makeSignless();
3213 BasicBlock* tmpBB = getBBVal($6);
3214 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
3216 $$.S.makeSignless();
3217 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
3219 for (; I != E; ++I) {
3220 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
3221 S->addCase(CI, I->second);
3223 error("Switch case is constant, but not a simple integer");
3227 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
3229 Value* tmpVal = getVal($2.T, $3);
3230 $6.S.makeSignless();
3231 BasicBlock* tmpBB = getBBVal($6);
3232 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
3234 $$.S.makeSignless();
3236 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
3237 TO LABEL ValueRef Unwind LABEL ValueRef {
3238 const PointerType *PFTy;
3239 const FunctionType *Ty;
3242 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3243 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3244 // Pull out the types of all of the arguments...
3245 std::vector<const Type*> ParamTypes;
3246 FTySign.makeComposite($3.S);
3248 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3250 ParamTypes.push_back((*I).V->getType());
3254 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3255 if (isVarArg) ParamTypes.pop_back();
3256 Ty = FunctionType::get($3.PAT->get(), ParamTypes, isVarArg);
3257 PFTy = PointerType::getUnqual(Ty);
3261 // Get the signedness of the result type. $3 is the pointer to the
3262 // function type so we get the 0th element to extract the function type,
3263 // and then the 0th element again to get the result type.
3264 $$.S.copy($3.S.get(0).get(0));
3267 $4.S.makeComposite(FTySign);
3268 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3269 BasicBlock *Normal = getBBVal($10);
3270 BasicBlock *Except = getBBVal($13);
3272 // Create the call node...
3273 if (!$6) { // Has no arguments?
3274 std::vector<Value*> Args;
3275 $$.TI = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
3276 } else { // Has arguments?
3277 // Loop through FunctionType's arguments and ensure they are specified
3280 FunctionType::param_iterator I = Ty->param_begin();
3281 FunctionType::param_iterator E = Ty->param_end();
3282 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3284 std::vector<Value*> Args;
3285 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
3286 if ((*ArgI).V->getType() != *I)
3287 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3288 (*I)->getDescription() + "'");
3289 Args.push_back((*ArgI).V);
3292 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
3293 error("Invalid number of parameters detected");
3295 $$.TI = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
3297 cast<InvokeInst>($$.TI)->setCallingConv(upgradeCallingConv($2));
3298 if ($2 == OldCallingConv::CSRet) {
3299 ParamAttrsVector Attrs;
3300 ParamAttrsWithIndex PAWI;
3301 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
3302 Attrs.push_back(PAWI);
3303 cast<InvokeInst>($$.TI)->setParamAttrs(ParamAttrsList::get(Attrs));
3307 lastCallingConv = OldCallingConv::C;
3310 $$.TI = new UnwindInst();
3311 $$.S.makeSignless();
3314 $$.TI = new UnreachableInst();
3315 $$.S.makeSignless();
3320 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
3323 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
3326 error("May only switch on a constant pool value");
3328 $6.S.makeSignless();
3329 BasicBlock* tmpBB = getBBVal($6);
3330 $$->push_back(std::make_pair(V, tmpBB));
3332 | IntType ConstValueRef ',' LABEL ValueRef {
3333 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
3335 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
3338 error("May only switch on a constant pool value");
3340 $5.S.makeSignless();
3341 BasicBlock* tmpBB = getBBVal($5);
3342 $$->push_back(std::make_pair(V, tmpBB));
3347 : OptAssign InstVal {
3350 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
3351 if (BCI->getSrcTy() == BCI->getDestTy() &&
3352 BCI->getOperand(0)->getName() == $1)
3353 // This is a useless bit cast causing a name redefinition. It is
3354 // a bit cast from a type to the same type of an operand with the
3355 // same name as the name we would give this instruction. Since this
3356 // instruction results in no code generation, it is safe to omit
3357 // the instruction. This situation can occur because of collapsed
3358 // type planes. For example:
3359 // %X = add int %Y, %Z
3360 // %X = cast int %Y to uint
3361 // After upgrade, this looks like:
3362 // %X = add i32 %Y, %Z
3363 // %X = bitcast i32 to i32
3364 // The bitcast is clearly useless so we omit it.
3368 $$.S.makeSignless();
3370 ValueInfo VI; VI.V = $2.I; VI.S.copy($2.S);
3371 setValueName(VI, $1);
3377 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
3378 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
3381 Value* tmpVal = getVal($1.PAT->get(), $3);
3382 $5.S.makeSignless();
3383 BasicBlock* tmpBB = getBBVal($5);
3384 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
3387 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
3390 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
3391 $6.S.makeSignless();
3392 BasicBlock* tmpBB = getBBVal($6);
3393 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
3397 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
3398 $$ = new std::vector<ValueInfo>();
3401 | ValueRefList ',' ResolvedVal {
3406 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
3409 | /*empty*/ { $$ = 0; }
3422 : ArithmeticOps Types ValueRef ',' ValueRef {
3425 const Type* Ty = $2.PAT->get();
3426 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<VectorType>(Ty))
3427 error("Arithmetic operator requires integer, FP, or packed operands");
3428 if (isa<VectorType>(Ty) &&
3429 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3430 error("Remainder not supported on vector types");
3431 // Upgrade the opcode from obsolete versions before we do anything with it.
3432 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3433 Value* val1 = getVal(Ty, $3);
3434 Value* val2 = getVal(Ty, $5);
3435 $$.I = BinaryOperator::create(Opcode, val1, val2);
3437 error("binary operator returned null");
3441 | LogicalOps Types ValueRef ',' ValueRef {
3444 const Type *Ty = $2.PAT->get();
3445 if (!Ty->isInteger()) {
3446 if (!isa<VectorType>(Ty) ||
3447 !cast<VectorType>(Ty)->getElementType()->isInteger())
3448 error("Logical operator requires integral operands");
3450 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3451 Value* tmpVal1 = getVal(Ty, $3);
3452 Value* tmpVal2 = getVal(Ty, $5);
3453 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3455 error("binary operator returned null");
3459 | SetCondOps Types ValueRef ',' ValueRef {
3462 const Type* Ty = $2.PAT->get();
3463 if(isa<VectorType>(Ty))
3464 error("VectorTypes currently not supported in setcc instructions");
3465 unsigned short pred;
3466 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3467 Value* tmpVal1 = getVal(Ty, $3);
3468 Value* tmpVal2 = getVal(Ty, $5);
3469 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3471 error("binary operator returned null");
3472 $$.S.makeUnsigned();
3475 | ICMP IPredicates Types ValueRef ',' ValueRef {
3478 const Type *Ty = $3.PAT->get();
3479 if (isa<VectorType>(Ty))
3480 error("VectorTypes currently not supported in icmp instructions");
3481 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3482 error("icmp requires integer or pointer typed operands");
3483 Value* tmpVal1 = getVal(Ty, $4);
3484 Value* tmpVal2 = getVal(Ty, $6);
3485 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3486 $$.S.makeUnsigned();
3489 | FCMP FPredicates Types ValueRef ',' ValueRef {
3492 const Type *Ty = $3.PAT->get();
3493 if (isa<VectorType>(Ty))
3494 error("VectorTypes currently not supported in fcmp instructions");
3495 else if (!Ty->isFloatingPoint())
3496 error("fcmp instruction requires floating point operands");
3497 Value* tmpVal1 = getVal(Ty, $4);
3498 Value* tmpVal2 = getVal(Ty, $6);
3499 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3500 $$.S.makeUnsigned();
3504 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3505 const Type *Ty = $2.V->getType();
3506 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3508 error("Expected integral type for not instruction");
3509 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3511 error("Could not create a xor instruction");
3514 | ShiftOps ResolvedVal ',' ResolvedVal {
3515 if (!$4.V->getType()->isInteger() ||
3516 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3517 error("Shift amount must be int8");
3518 const Type* Ty = $2.V->getType();
3519 if (!Ty->isInteger())
3520 error("Shift constant expression requires integer operand");
3521 Value* ShiftAmt = 0;
3522 if (cast<IntegerType>(Ty)->getBitWidth() > Type::Int8Ty->getBitWidth())
3523 if (Constant *C = dyn_cast<Constant>($4.V))
3524 ShiftAmt = ConstantExpr::getZExt(C, Ty);
3526 ShiftAmt = new ZExtInst($4.V, Ty, makeNameUnique("shift"), CurBB);
3529 $$.I = BinaryOperator::create(getBinaryOp($1, Ty, $2.S), $2.V, ShiftAmt);
3532 | CastOps ResolvedVal TO Types {
3533 const Type *DstTy = $4.PAT->get();
3534 if (!DstTy->isFirstClassType())
3535 error("cast instruction to a non-primitive type: '" +
3536 DstTy->getDescription() + "'");
3537 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3541 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3542 if (!$2.V->getType()->isInteger() ||
3543 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3544 error("select condition must be bool");
3545 if ($4.V->getType() != $6.V->getType())
3546 error("select value types should match");
3547 $$.I = new SelectInst($2.V, $4.V, $6.V);
3550 | VAARG ResolvedVal ',' Types {
3551 const Type *Ty = $4.PAT->get();
3553 $$.I = new VAArgInst($2.V, Ty);
3557 | VAARG_old ResolvedVal ',' Types {
3558 const Type* ArgTy = $2.V->getType();
3559 const Type* DstTy = $4.PAT->get();
3560 ObsoleteVarArgs = true;
3561 Function* NF = cast<Function>(CurModule.CurrentModule->
3562 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3565 //foo = alloca 1 of t
3569 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3570 CurBB->getInstList().push_back(foo);
3571 CallInst* bar = new CallInst(NF, $2.V);
3572 CurBB->getInstList().push_back(bar);
3573 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3574 $$.I = new VAArgInst(foo, DstTy);
3578 | VANEXT_old ResolvedVal ',' Types {
3579 const Type* ArgTy = $2.V->getType();
3580 const Type* DstTy = $4.PAT->get();
3581 ObsoleteVarArgs = true;
3582 Function* NF = cast<Function>(CurModule.CurrentModule->
3583 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3585 //b = vanext a, t ->
3586 //foo = alloca 1 of t
3589 //tmp = vaarg foo, t
3591 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3592 CurBB->getInstList().push_back(foo);
3593 CallInst* bar = new CallInst(NF, $2.V);
3594 CurBB->getInstList().push_back(bar);
3595 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3596 Instruction* tmp = new VAArgInst(foo, DstTy);
3597 CurBB->getInstList().push_back(tmp);
3598 $$.I = new LoadInst(foo);
3602 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3603 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3604 error("Invalid extractelement operands");
3605 $$.I = new ExtractElementInst($2.V, $4.V);
3606 $$.S.copy($2.S.get(0));
3608 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3609 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3610 error("Invalid insertelement operands");
3611 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3614 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3615 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3616 error("Invalid shufflevector operands");
3617 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3621 const Type *Ty = $2.P->front().first->getType();
3622 if (!Ty->isFirstClassType())
3623 error("PHI node operands must be of first class type");
3624 PHINode *PHI = new PHINode(Ty);
3625 PHI->reserveOperandSpace($2.P->size());
3626 while ($2.P->begin() != $2.P->end()) {
3627 if ($2.P->front().first->getType() != Ty)
3628 error("All elements of a PHI node must be of the same type");
3629 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3634 delete $2.P; // Free the list...
3636 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3637 // Handle the short call syntax
3638 const PointerType *PFTy;
3639 const FunctionType *FTy;
3641 if (!(PFTy = dyn_cast<PointerType>($3.PAT->get())) ||
3642 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3643 // Pull out the types of all of the arguments...
3644 std::vector<const Type*> ParamTypes;
3645 FTySign.makeComposite($3.S);
3647 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3649 ParamTypes.push_back((*I).V->getType());
3654 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3655 if (isVarArg) ParamTypes.pop_back();
3657 const Type *RetTy = $3.PAT->get();
3658 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3659 error("Functions cannot return aggregate types");
3661 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg);
3662 PFTy = PointerType::getUnqual(FTy);
3666 // Get the signedness of the result type. $3 is the pointer to the
3667 // function type so we get the 0th element to extract the function type,
3668 // and then the 0th element again to get the result type.
3669 $$.S.copy($3.S.get(0).get(0));
3671 $4.S.makeComposite(FTySign);
3673 // First upgrade any intrinsic calls.
3674 std::vector<Value*> Args;
3676 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3677 Args.push_back((*$6)[i].V);
3678 Instruction *Inst = upgradeIntrinsicCall(FTy->getReturnType(), $4, Args);
3680 // If we got an upgraded intrinsic
3684 // Get the function we're calling
3685 Value *V = getVal(PFTy, $4);
3687 // Check the argument values match
3688 if (!$6) { // Has no arguments?
3689 // Make sure no arguments is a good thing!
3690 if (FTy->getNumParams() != 0)
3691 error("No arguments passed to a function that expects arguments");
3692 } else { // Has arguments?
3693 // Loop through FunctionType's arguments and ensure they are specified
3696 FunctionType::param_iterator I = FTy->param_begin();
3697 FunctionType::param_iterator E = FTy->param_end();
3698 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3700 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3701 if ((*ArgI).V->getType() != *I)
3702 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3703 (*I)->getDescription() + "'");
3705 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3706 error("Invalid number of parameters detected");
3709 // Create the call instruction
3710 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
3711 CI->setTailCall($1);
3712 CI->setCallingConv(upgradeCallingConv($2));
3716 // Deal with CSRetCC
3717 if ($2 == OldCallingConv::CSRet) {
3718 ParamAttrsVector Attrs;
3719 ParamAttrsWithIndex PAWI;
3720 PAWI.index = 1; PAWI.attrs = ParamAttr::StructRet; // first arg
3721 Attrs.push_back(PAWI);
3722 cast<CallInst>($$.I)->setParamAttrs(ParamAttrsList::get(Attrs));
3726 lastCallingConv = OldCallingConv::C;
3734 // IndexList - List of indices for GEP based instructions...
3736 : ',' ValueRefList { $$ = $2; }
3737 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3741 : VOLATILE { $$ = true; }
3742 | /* empty */ { $$ = false; }
3746 : MALLOC Types OptCAlign {
3747 const Type *Ty = $2.PAT->get();
3748 $$.S.makeComposite($2.S);
3749 $$.I = new MallocInst(Ty, 0, $3);
3752 | MALLOC Types ',' UINT ValueRef OptCAlign {
3753 const Type *Ty = $2.PAT->get();
3754 $5.S.makeUnsigned();
3755 $$.S.makeComposite($2.S);
3756 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3759 | ALLOCA Types OptCAlign {
3760 const Type *Ty = $2.PAT->get();
3761 $$.S.makeComposite($2.S);
3762 $$.I = new AllocaInst(Ty, 0, $3);
3765 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3766 const Type *Ty = $2.PAT->get();
3767 $5.S.makeUnsigned();
3768 $$.S.makeComposite($4.S);
3769 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3772 | FREE ResolvedVal {
3773 const Type *PTy = $2.V->getType();
3774 if (!isa<PointerType>(PTy))
3775 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3776 $$.I = new FreeInst($2.V);
3777 $$.S.makeSignless();
3779 | OptVolatile LOAD Types ValueRef {
3780 const Type* Ty = $3.PAT->get();
3782 if (!isa<PointerType>(Ty))
3783 error("Can't load from nonpointer type: " + Ty->getDescription());
3784 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3785 error("Can't load from pointer of non-first-class type: " +
3786 Ty->getDescription());
3787 Value* tmpVal = getVal(Ty, $4);
3788 $$.I = new LoadInst(tmpVal, "", $1);
3789 $$.S.copy($3.S.get(0));
3792 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3794 const PointerType *PTy = dyn_cast<PointerType>($5.PAT->get());
3796 error("Can't store to a nonpointer type: " +
3797 $5.PAT->get()->getDescription());
3798 const Type *ElTy = PTy->getElementType();
3799 Value *StoreVal = $3.V;
3800 Value* tmpVal = getVal(PTy, $6);
3801 if (ElTy != $3.V->getType()) {
3802 PTy = PointerType::getUnqual(StoreVal->getType());
3803 if (Constant *C = dyn_cast<Constant>(tmpVal))
3804 tmpVal = ConstantExpr::getBitCast(C, PTy);
3806 tmpVal = new BitCastInst(tmpVal, PTy, "upgrd.cast", CurBB);
3808 $$.I = new StoreInst(StoreVal, tmpVal, $1);
3809 $$.S.makeSignless();
3812 | GETELEMENTPTR Types ValueRef IndexList {
3814 const Type* Ty = $2.PAT->get();
3815 if (!isa<PointerType>(Ty))
3816 error("getelementptr insn requires pointer operand");
3818 std::vector<Value*> VIndices;
3819 upgradeGEPInstIndices(Ty, $4, VIndices);
3821 Value* tmpVal = getVal(Ty, $3);
3822 $$.I = new GetElementPtrInst(tmpVal, VIndices.begin(), VIndices.end());
3823 ValueInfo VI; VI.V = tmpVal; VI.S.copy($2.S);
3824 $$.S.copy(getElementSign(VI, VIndices));
3832 int yyerror(const char *ErrorMsg) {
3834 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3835 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3836 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3837 if (yychar != YYEMPTY && yychar != 0)
3838 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3840 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3841 std::cout << "llvm-upgrade: parse failed.\n";
3845 void warning(const std::string& ErrorMsg) {
3847 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3848 + ":" + llvm::utostr((unsigned) Upgradelineno) + ": ";
3849 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3850 if (yychar != YYEMPTY && yychar != 0)
3851 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3853 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3856 void error(const std::string& ErrorMsg, int LineNo) {
3857 if (LineNo == -1) LineNo = Upgradelineno;
3858 Upgradelineno = LineNo;
3859 yyerror(ErrorMsg.c_str());